What's the easiest way to save UIColor into NSUserDefaults ?
And how to re-create it from NSUserDefaults?
Many thanks for reading
What's the easiest way to save UIColor into NSUserDefaults ?
And how to re-create it from NSUserDefaults?
Many thanks for reading
Edit 2: I seem to have found the answer. Check out the article by Erica Sadun on extending UIColor.
Edit: This code does not seem to work for a UIColor Object. Not sure why...
Here is some code to take a look at:
Saving an object into NSUserDefaults:
NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
[userDefaults setObject:someColorObject forKey:@"myColor"];
Reading an object from NSUserDefaults:
NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
UIColor *someColor = (UIColor *)[userDefaults objectForKey:@"myColor"];
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];
I've got the answer by myself
Save
const CGFloat *components = CGColorGetComponents(pColor.CGColor);
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setFloat:components[0] forKey:@"cr"];
[prefs setFloat:components[1] forKey:@"cg"];
[prefs setFloat:components[2] forKey:@"cb"];
[prefs setFloat:components[3] forKey:@"ca"];
Load
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
UIColor* tColor = [UIColor colorWithRed:[prefs floatForKey:@"cr"] green:[prefs floatForKey:@"cg"] blue:[prefs floatForKey:@"cb"] alpha:[prefs floatForKey:@"ca"]];
Thanks for Erica's UIColor category. I did not really like saving 4 floats in the preferences, and just wanted a single entry.
So using Erica's UIColor category, I was able to convert the RGB color to/from an NSString which can be saved in the preferences.
// Save a color
NSString *theColorStr = [self.artistColor stringFromColor];
[[NSUserDefaults standardUserDefaults] setObject:theColorStr forKey:@"myColor"];
// Read a color
NSString *theColorStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"myColor"];
if ([theColorStr length] > 0) {
self.myColor = [UIColor colorWithString:theColorStr];
} else {
self.myColor = [UIColor colorWithRed:88.0/255.0 green:151.0/255.0 blue:237.0/255.0 alpha:1.0];
}