将 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加载
发布评论