如何在NSUserDefaults中存储和加载backgroundColor

时间:2011-04-02 04:47:40

标签: ios nsuserdefaults background-color

商店 -

-(IBAction) setMyColor:(id)sender{

if (sender == yellowButton ) {
    [colorView setBackgroundColor:[UIColor yellowColor]];
}

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
UIColor *strColor = [colorView backgroundColor];
[userDefaults setObject:strColor forKey:@"myColor"];
[userDefaults synchronize];

}

加载 -

- (void)viewDidLoad {   

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[colorView setBackgroundColor[UIColor [userDefaults objectForKey:@"myColor"]]];

[super viewDidLoad];

}

但它无法运行...... 也许问题是'如何从UIView获取backgroundColor值?

1 个答案:

答案 0 :(得分:13)

你可以使用

//save     
    NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:color];
    [[NSUserDefaults standardUserDefaults] setObject:colorData forKey:@"myColor"];

//retrieve
    NSData *colorData = [[NSUserDefaults standardUserDefaults] objectForKey:@"myColor"];
    UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];

or 

//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"];

//retrieve
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
UIColor* tColor = [UIColor colorWithRed:[prefs floatForKey:@"cr"] green:[prefs floatForKey:@"cg"] blue:[prefs floatForKey:@"cb"] alpha:[prefs floatForKey:@"ca"]];