What's the easiest way to save a UIColor into NSUserDefaults and then get it back out?
What's the easiest way to save a UIColor into NSUserDefaults and then get it back out?
private let colorPickerKey = "ColorPickerKey"
var selectedColor: UIColor? {
get {
guard let colorData = UserDefaults.standard.object(forKey: colorPickerKey) as? Data,
let color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor else { return nil }
return color
} set {
guard let newValue = newValue else {
UserDefaults.standard.removeObject(forKey: colorPickerKey)
return
}
let colorData = NSKeyedArchiver.archivedData(withRootObject: newValue)
UserDefaults.standard.set(colorData, forKey: colorPickerKey)
}
}