What's the easiest way to save a UIColor
into NSUserDefaults
and then get it back out?
There's no straight way to save UIColor with UserDefaults so we will have to manipulate the type a bit. We are going to convert UIColor to Data and save it as any? . To convert the type of UIColor , we will need to use a special method called NSKeyedArchiver . Therefore, let's make an extension to the UserDefaults .
All the contents saved by NSUserDefaults is saved inside a plist file that can be found under Library -> Preferences -> $AppBundleId.
static func setObject(value:AnyObject ,key:String) { let pref = NSUserDefaults. standardUserDefaults() pref. setObject(value, forKey: key) pref. synchronize() } static func getObject(key:String) -> AnyObject { let pref = NSUserDefaults.
Overview. The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an app to customize its behavior to match a user's preferences. For example, you can allow users to specify their preferred units of measurement or media playback speed.
One way of doing it might be to archive it (like with NSColor, though I haven't tested this):
NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:color]; [[NSUserDefaults standardUserDefaults] setObject:colorData forKey:@"myColor"];
And to get it back:
NSData *colorData = [[NSUserDefaults standardUserDefaults] objectForKey:@"myColor"]; UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With