如何在plist文件中保存UISwitch状态?

时间:2012-12-10 10:48:47

标签: iphone objective-c xcode plist uiswitch

我正在尝试保存UISwitch的状态。如果UISwitch状态为“ON”,当用户退出应用程序并再次启动时...应用程序应显示之前的状态,如果用户计划将UISwitch的状态更改为“OFF” ..他应该收到一条消息,说他之前有“ON”状态并更改为状态“OFF”

如果你们帮助我,那就太棒了。谢谢

-(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];
    }
}

1 个答案:

答案 0 :(得分:1)

更改按钮操作方法,如:

-(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];
    }
}

如果您想获取存储的数据,可以使用:

 NSUserDefaults* defaults  = [NSUserDefaults standardUserDefaults];
 BOOL previousState = [defaults boolForKey:@"switchValueKey"];