Reputation: 117
For some reason using NSUserDefaults to save the state of my switch and my label don't seem to be working. I can save the state of my switch and load it however unless i manually change the state of the switch the label will not change to on or off.
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
self->switch1.on = ([[standardDefaults stringForKey:@"switchKey"]
isEqualToString:@"On"]) ? (YES) : (NO);
As you can see i added in label.text = @"OFF" when the switch is off but however it still doesn't change.
- (IBAction)switchChanged:(UISwitch *)sender {
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
if (sender.on == 0) {
label.text = @"OFF";
[standardDefaults setObject:@"Off" forKey:@"switchKey"];
} else if (sender.on == 1) {
label.text = @"ON";
[standardDefaults setObject:@"On" forKey:@"switchKey"];
}
[standardDefaults synchronize];
}
Before i wanted to save the switch state i just used this.
-(IBAction) alarmSettings1{
if (switch1.on)
{ label.text = @"ON";}
else { label.text = @"OFF";}
}
I know I'm just doing something simple wrong but can't figure out what.
Upvotes: 1
Views: 46
Reputation: 2110
You should set your boolean like so:
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"switchKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
So when you want to set the state of your switch, you would do:
BOOL switchState = [[NSUserDefaults standardUserDefaults] objectForKey:@"switchKey"];
self.switch1.on = switchState;
Also, in your IBAction
method, read the state like so:
- (IBAction)switchChanged:(UISwitch *)sender {
label.text = sender.on ? @"ON" : @"OFF";
[[NSUserDefaults standardUserDefaults] setBool:sender.on forKey:@"switchKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
Upvotes: 0