将 UIColor 保存到 NSUserDefaults 并从 NSUserDefaults 加载 [英] Saving UIColor to and loading from NSUserDefaults
问题描述
将 UIColor
保存到 NSUserDefaults
中,然后将其取回的最简单方法是什么?
What's the easiest way to save a UIColor
into NSUserDefaults
and then get it back out?
推荐答案
有了接受的答案,你会很快最终得到了很多 NSKeyed 档案 &取消归档您的所有代码.更简洁的解决方案是扩展 UserDefaults.这正是扩展的用途;UserDefaults 可能不了解 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 UserDefaults. This is exactly what extensions are for; UserDefaults probably doesn't know about UIColor as it is because UIKit and Foundation are different frameworks.
extension UserDefaults {
func color(forKey key: String) -> UIColor? {
var color: UIColor?
if let colorData = data(forKey: key) {
color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor
}
return color
}
func set(_ value: UIColor?, forKey key: String) {
var colorData: Data?
if let color = value {
colorData = NSKeyedArchiver.archivedData(withRootObject: color)
}
set(colorData, forKey: key)
}
}
斯威夫特 4.2
extension UserDefaults {
func color(forKey key: String) -> UIColor? {
guard let colorData = data(forKey: key) else { return nil }
do {
return try NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: colorData)
} catch let error {
print("color error (error.localizedDescription)")
return nil
}
}
func set(_ value: UIColor?, forKey key: String) {
guard let color = value else { return }
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: false)
set(data, forKey: key)
} catch let error {
print("error color key data not saved (error.localizedDescription)")
}
}
}
用法
UserDefaults.standard.set(UIColor.white, forKey: "white")
let whiteColor = UserDefaults.standard.color(forKey: "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 加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!