views:

1805

answers:

4

What's the easiest way to save UIColor into NSUserDefaults ?

And how to re-create it from NSUserDefaults?

Many thanks for reading

A: 

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"];
zPesk
I appreicate for your help, but it seems that NSUserDefaults can't save UIColor object
Unreality
hmm let me try the code i posted above - i just wrote it from memory.
zPesk
it seems your right - let me see if i can find a work around
zPesk
check out the article i linked to in the post body
zPesk
+1  A: 

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];
Wevah
+1  A: 

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"]];
Unreality
The only issue that could arise is if the underlying CGColor isn't in the RGB colorspace. If you're certain it will be RGB, this is probably a nicer option than archival.
Wevah
+2  A: 

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];
}
lifjoy