I did a thorough research, but didn't seem to find the answer i'm looking for. Hope someone can help.
I have multiple view controllers in my app, one of which is an 'options' view in which users can change certain settings like the background color through a segmented control. Once clicked, users click on a button to save their preference color to NSUserDefaults. This works perfectly and the next time the app opens, the right color is still selected. But only in the options view controller.
How can I get this selected background color to load in my other view controllers? I don't seem to get it running by implementing it into the ViewDidLoad of my other views, as I've done in the options view (see below).
My code in the options.m is as follows:
- (IBAction)changeColor {
switch (colorControl.selectedSegmentIndex) {
case 0:
[colorView setBackgroundColor:[UIColor redColor]];
break;
case 1:
[colorView setBackgroundColor:[UIColor blackColor]];
break;
case 2:
[colorView setBackgroundColor:[UIColor brownColor]];
break;
default:
break;
}
}
- (IBAction)saveDefaultColor {
int defaultColorInteger = colorControl.selectedSegmentIndex;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:defaultColorInteger forKey:@"defaultColor"];
[userDefaults synchronize];
}
The above are the control and save button. In my ViewDidLoad I've included the following:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
int defaultColorInteger = [userDefaults integerForKey:@"defaultColor"];
[colorControl setSelectedSegmentIndex:defaultColorInteger];
switch (colorControl.selectedSegmentIndex) {
case 0:
[colorView setBackgroundColor:[UIColor redColor]];
break;
case 1:
[colorView setBackgroundColor:[UIColor blackColor]];
break;
case 2:
[colorView setBackgroundColor:[UIColor brownColor]];
break;
default:
break;
This works exactly as I want it to, but I can't get it working in my other views. Can anyone help me with what I seem to be missing? Many thanks
I think you need to check the key values in other views, because NSUserDefaults save data for the whole application not for a single view. May be you are not putting the keys properly.