Cocoa Quickies: Store an NSColor with NSUserDefaults
It might seem logical that NSColor would encode easily to NSUserDefaults using -setObjectForKey, but trying to do that will quickly raise an exception. It won’t work because it is not one of the core data types (NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary) which can be saved into property list (plist) files.
If you need to save an NSColor to your cocoa app’s preferences file, you’ll need to store the actual color values individually. Below is an example of how you can store a basic NSColor composed of RGBA values with NSUserDefaults. You can use these methods as they are or perhaps expand them to be additions to the NSUserDefaults class, whichever strikes your fancy:
-(void)userDefaultsSetColor: (NSColor*)color forKey:(NSString*)key
{
NSArray *colorValues = [NSArray arrayWithObjects:
[NSNumber numberWithFloat: [color redComponent]],
[NSNumber numberWithFloat: [color greenComponent]],
[NSNumber numberWithFloat: [color blueComponent]],
[NSNumber numberWithFloat: [color alphaComponent]],
nil];
[[NSUserDefaults standardUserDefaults] setObject: colorValues
forKey: key];
}
-(NSColor*)userDefaultsColorForKey:(NSString*)key
{
NSArray *colorValues = [[NSUserDefaults standardUserDefaults] objectForKey: key];
if(colorValues && ([colorValues count] >= 4))
{
return [NSColor colorWithDeviceRed: [[colorValues objectAtIndex: 0] floatValue]
green: [[colorValues objectAtIndex: 1] floatValue]
blue: [[colorValues objectAtIndex: 2] floatValue]
alpha: [[colorValues objectAtIndex: 3] floatValue]];
}
else
return nil;
}