开发者

How to save custom color to UserDefaults

I am trying to use some non-standard colors (i.e. not UIColor blueColor, but a darker blue color, a darker green, red...etc...) and when I try to save the user selected UIColor object to UserDefaults, it is failing. Below is the code I am using to create the custom colors, followed by the code to save the UIColor objects to the UserDefaults.

Any help would be appreciated.

Thanks!

// create the custom color

UIColor *selectedColor = [UIColor colorWithRed:0.0 green:0.5 blue:0.0 alpha:1.0];

// save the color to user defaults

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// archive it into a data object

/*** Fails on this next lin开发者_StackOverflow社区e ***/    
NSData *dataColor = [NSKeyedArchiver archivedDataWithRootObject: selectedColor];

// write the data into the user defaults
[prefs setObject: dataColor forKey:colorKey];

[prefs synchronize];


The problem here is that UIColor is not "key-coding" compliant (I am not sure about the correct term), you should have an error like this:

*** -[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value

It cannot be saved into NSUSerDefaults, you need to saved them using a NSKeyArchiver or convert the color values in to something key-code compliant. For example I have followed the NSStringFromCGRect approach using categories. This is my code:

UIColorAdditions.h

#import <Foundation/Foundation.h>


@interface UIColor (UIColorAdditions) 

+ (NSString *)stringFromUIColor:(UIColor *)color;

@end

@interface NSString (UIColorAdditions) 

+ (UIColor *)colorFromNSString:(NSString *)string;

@end

UIColorAdditions.m

#import "UIColorAdditions.h"

@implementation UIColor (UIColorAdditions)
+ (NSString *)stringFromUIColor:(UIColor *)color {
    return [NSString stringWithFormat:@"%@", color ];
}
@end

@implementation NSString (UIColorAdditions)
+ (UIColor*)colorFromNSString:(NSString *)string {
    // The string should be something like "UIDeviceRGBColorSpace 0.5 0 0.25 1
    NSArray *values = [string componentsSeparatedByString:@" "];
    CGFloat red = [[values objectAtIndex:1] floatValue];
    CGFloat green = [[values objectAtIndex:2] floatValue];
    CGFloat blue = [[values objectAtIndex:3] floatValue];
    CGFloat alpha = [[values objectAtIndex:4] floatValue];
    UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];

    return color;
}
@end

An example of use:

NSString *strColor = [UIColor stringFromUIColor:[UIColor colorWithRed:0.5 green:0 blue:0.25 alpha:1.0]];
[[NSUserDefaults standardUserDefaults] setObject:strColor forKey:kViewBgColorKey];

There are multiple solutions, (better ones), I just posted mine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜