Reputation: 161
i am trying to save the state of UISwitch .If the UISwitch state is "ON" and when the user quits the app and starts it again ..the app should show the previous state and if the user plans to change the state of UISwitch to "OFF"..he should get a message saying previously he had "ON" state and change to state to "OFF"
if you guys help me out that would be great .Thanks
-(IBAction)notification:(id)sender
{
if (sender == notifyMe)
{
if(notifyMe.isOn == YES)
{
toggle = YES;
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:notifyMe.on forKey:@"switchValueKey"];
[defaults synchronize];
NSLog(@"Notification is ON");
}
else
{
toggle = NO;
NSLog(@"Notification is OFF");
}
}
if ([cellDelegate respondsToSelector:@selector(notificationReqd:)])
{
[cellDelegate notificationReqd:self];
}
}
Upvotes: 0
Views: 398
Reputation: 107141
Change your button action method like:
-(IBAction)notification:(id)sender
{
if (sender == notifyMe)
{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
BOOL previousState = [defaults boolForKey:@"switchValueKey"];
if(notifyMe.isOn == YES)
{
toggle = YES;
NSLog(@"Notification is ON");
}
else
{
toggle = NO;
NSLog(@"Notification is OFF");
}
[defaults setBool:toggle forKey:@"switchValueKey"];
[defaults synchronize];
//You can show the message here
NSLog(@"Previous state was %d",previousState);
}
if ([cellDelegate respondsToSelector:@selector(notificationReqd:)])
{
[cellDelegate notificationReqd:self];
}
}
When you want to get the stored data you can use:
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
BOOL previousState = [defaults boolForKey:@"switchValueKey"];
Upvotes: 1