将UIColor保存到NSUserDefaults并从NSUserDefaults加载

编程入门 行业动态 更新时间:2024-10-28 09:15:43
本文介绍了将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加载

本文发布于:2023-07-16 14:40:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1122706.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并从   加载   UIColor   NSUserDefaults

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!