问题
I need some help to load and read UIColor from UserDefaults.
I found a nice extension to do that:
extension UserDefaults {
func colorForKey(key: String) -> UIColor? {
var color: UIColor?
if let colorData = data(forKey: key) {
color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor
}
return color
}
func setColor(color: UIColor?, forKey key: String) {
var colorData: NSData?
if let color = color {
colorData = NSKeyedArchiver.archivedData(withRootObject: color) as NSData?
}
set(colorData, forKey: key)
}
}
But NSKeyedUnarchiver.unarchiveObject was deprecated recently, so i don't know how to get data from it.
Any suggestions? Thank you!
回答1:
In your code, simply replace 2 lines, i.e
Replace
color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor
with
color = try! NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: colorData)
//// Here you can use try?
instead of try!
and wrap it in if-let
statement. Your choice.
and
Replace
colorData = NSKeyedArchiver.archivedData(withRootObject: color) as NSData?
with
colorData = try? NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: true)
Also, use Data
instead of NSData
in var colorData: NSData?
,i.e.
var colorData: Data?
回答2:
Simply do as do the deprecation messages tell you:
extension UserDefaults {
func colorForKey(key: String) -> UIColor? {
if let colorData = data(forKey: key),
let color = try? NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: colorData)
{
return color
} else {
return nil
}
}
// But why an Option<UIColor> here?
func setColor(color: UIColor?, forKey key: String) {
if let color = color,
let colorData = try? NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: true)
{
set(colorData, forKey: key)
}
}
}
来源:https://stackoverflow.com/questions/52999953/save-get-uicolor-from-userdefaults