【问题标题】:How to save UISwitch state on plist file?如何在 plist 文件中保存 UISwitch 状态?
【发布时间】:2012-12-10 10:48:47
【问题描述】:

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

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

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

【问题讨论】:

  • 您正在保存上述代码中的值。现在是什么问题?

标签: iphone objective-c xcode plist uiswitch


【解决方案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"];

【讨论】:

  • 我应该把最后两行放在 viewDidLoad 中吗?
  • @orgami:你想要的值,你可以在那里添加。如果您需要在 viewDidLoad 中检查它以设置以前的状态,则需要将其放在那里