如何将自定义颜色保存到UserDefaults

时间:2010-03-04 16:29:06

标签: uicolor

我正在尝试使用一些非标准颜色(即不是UIColor blueColor,而是深蓝色,深绿色,红色......等等)当我尝试将用户选择的UIColor对象保存到UserDefaults,它失败了。下面是我用来创建自定义颜色的代码,后面跟着将UIColor对象保存到UserDefaults的代码。

任何帮助都将不胜感激。

谢谢!

//创建自定义颜色

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

//将颜色保存为用户默认值

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

/*** Fails on this next line ***/    
NSData *dataColor = [NSKeyedArchiver archivedDataWithRootObject: selectedColor];

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

[prefs synchronize];

1 个答案:

答案 0 :(得分:5)

这里的问题是UIColor不符合“密钥编码”(我不确定正确的术语),你应该有这样的错误:

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

无法将其保存到NSUSerDefaults中,您需要使用NSKeyArchiver保存它们或将颜色值转换为符合键码的内容。例如,我使用类别遵循NSStringFromCGRect方法。这是我的代码:

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

使用示例:

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

有多种解决方案,(更好的解决方案),我刚刚发布了。