Reputation: 49
If I were to switch my UISwitch
controller to "off" and leave the view controller and come back to the view controller it will show the UISwitch
is "on" (default value) instead of "off". How do I save the value of the UISwitch controller when switching from/to view controllers?
- (void)controlsEnabled:(BOOL)enabled
{
self.onandoffSwitch.enabled = enabled;
if (enabled)
{
NSLog(@"ON");
}
else
{
NSLog(@"OFF");
}
}
Upvotes: 0
Views: 958
Reputation: 104082
The most likely reason for the switch state not persisting, is that you're creating a new instance (with the default switch state) of the controller, rather than going back to the one you originally came from. If you're using segues, they always instantiate new controllers when you perform them (except for unwind segues). Also modally presented controllers are deallocated when you dismiss them, unless you keep a strong reference to them somewhere. So, how to make the switch maintain its state depends on whether you want to go back to the same instance, and how you go about doing that.
Upvotes: 0
Reputation: 7845
You need to persist the setting in some way. Here's an example using NSUserDefaults
:
[[NSUserDefaults standardUserDefaults] setBool:yourSwitch.on forKey:@"switchValue"];
[[NSUserDefaults standardUserDefaults] synchronize];
And read it when you load the view hierarchy again:
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
BOOL state = [[NSUserDefaults standardUserDefaults] boolForKey:@"switchValue"];
Upvotes: 5