Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store and load backgroundColor in NSUserDefaults

store -

-(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];

}

load -

- (void)viewDidLoad {   

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

[super viewDidLoad];

}

but it failed to run ... maybe the question is 'how to get the backgroundColor value from UIView'?

like image 852
Jimi Avatar asked Apr 02 '11 04:04

Jimi


1 Answers

you can use

//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"]];
like image 138
Sergnsk Avatar answered Oct 24 '22 14:10

Sergnsk