到NSUserDefaults并从NSUserDefaults加

到NSUserDefaults并从NSUserDefaults加

本文介绍了将UIColor保存到NSUserDefaults并从NSUserDefaults加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

UIColor 保存到 NSUserDefaults 然后将其恢复出来最简单的方法是什么?

What's the easiest way to save a UIColor into NSUserDefaults and then get it back out?

推荐答案

通过,你很快会得到很多NSKeyed档案&取消归档所有的代码。一个更清洁的解决方案是扩展NSUserDefaults。这正是扩展是什么; NSUserDefaults可能不知道UIColor,因为它是因为UIKit和Foundation是不同的框架。

With the accepted answer, you'll quickly end up with a lot of NSKeyed archives & unarchives all over your code. A cleaner solution is to extend NSUserDefaults. This is exactly what extensions are for; NSUserDefaults probably doesn't know about UIColor as it is because UIKit and Foundation are different frameworks.

extension NSUserDefaults {

    func colorForKey(key: String) -> UIColor? {
        var color: UIColor?
        if let colorData = dataForKey(key) {
            color = NSKeyedUnarchiver.unarchiveObjectWithData(colorData) as? UIColor
        }
        return color
    }

    func setColor(color: UIColor?, forKey key: String) {
        var colorData: NSData?
        if let color = color {
            colorData = NSKeyedArchiver.archivedDataWithRootObject(color)
        }
        setObject(colorData, forKey: key)
    }

}



使用



Usage

NSUserDefaults.standardUserDefaults().setColor(UIColor.whiteColor(), forKey: "white")
let whiteColor = NSUserDefaults.standardUserDefaults().colorForKey("white")

这也可以在具有类别的Objective-C中完成。

This can also be done in Objective-C with a category.

我已将添加为Swift文档。

I've added the Swift file as a gist here.

这篇关于将UIColor保存到NSUserDefaults并从NSUserDefaults加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 15:38