Reputation: 157
I have managed to change the state of my UISwitch
and save to NSUserDefaults
.
My UISwitch
is in a different view from the main view and when I flip between views, my UISwitch
button always appears ON even though the state may be OFF.
- (IBAction)truthonoff:(id)sender {
if(_truthonoff.on) {
// lights on
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:@"yes" forKey:@"truthonoff"];
[defaults synchronize];
self.status.text = @"on";
}
else {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:@"no" forKey:@"truthonoff"];
[defaults synchronize];
self.status.text =@"off";
}
}
And this is how I'm loading the button in the second view controller:
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
self.text.text=[defaults objectForKey:@"truthonoff"];
How can I ensure the UISwitch
state represents the value in the NSUserDefaults
(i.e. when it's OFF it shows as OFF and when ON shows as ON)?
Upvotes: 2
Views: 515
Reputation: 45490
A little too late but Instead of doing like the answer you have accepted:
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject: tswitch.isOn ? @"YES" : @"NO" forKey:@"truthonoff"];
[defaults synchronize];
the right way would be:
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setBool:tswitch.isOn forKey:@"truthonoff"];
[defaults synchronize];
This save you from checking the value of the boolean, since NSUserDefaults
can take boolean
value.
Also it would be easier to retrieve the boolean:
bool truthonoff = [defaults boolForKey:@"truthonoff"];
Read up some more on boolForKey
Upvotes: 1
Reputation: 11197
Try this:
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[self.valueSwitch setOn:[[defaults objectForKey:@"truthonoff"] boolValue] animated:YES];
[self.valueSwitch addTarget:self action:@selector(stateSwitched:) forControlEvents:UIControlEventValueChanged];
In stateSwitched
do this:
-(void)stateSwitched:(id)sender {
UISwitch *tswitch = (UISwitch *)sender;
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject: tswitch.isOn ? @"YES" : @"NO" forKey:@"truthonoff"];
[defaults synchronize];
}
Hope this helps .. :)
Upvotes: 3
Reputation: 1865
Connect your your UISwitch
to an IBOutlet
in your ViewController
.
You can (un-)set the switch with:
[mySwitch setOn:TRUE animated:TRUE];
Upvotes: 0