Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving UIColor to and loading from NSUserDefaults

What's the easiest way to save a UIColor into NSUserDefaults and then get it back out?

like image 488
Unreality Avatar asked Aug 14 '09 01:08

Unreality


People also ask

How do you save UIColor in UserDefaults?

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 .

Where are the NSUserDefaults values stored?

All the contents saved by NSUserDefaults is saved inside a plist file that can be found under Library -> Preferences -> $AppBundleId.

How do you save NSUserDefaults in Objective C?

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.

What is NSUserDefaults in Swift?

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.


1 Answers

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]; 
like image 86
Wevah Avatar answered Sep 16 '22 17:09

Wevah