从NSUserDefaults加载UISwitch的状态

时间:2014-03-23 00:30:01

标签: ios objective-c nsuserdefaults uiswitch

我设法更改了UISwitch的状态并保存到NSUserDefaults

我的UISwitch与主视图位于不同的视图中,当我在视图之间切换时,即使状态可能为OFF,我的UISwitch按钮也始终显示为ON。

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

这就是我在第二个视图控制器中加载按钮的方式:

NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
self.text.text=[defaults objectForKey:@"truthonoff"];

如何确保UISwitch状态代表NSUserDefaults中的值(即当它关闭时显示为OFF并且当ON显示为ON时)?

3 个答案:

答案 0 :(得分:3)

试试这个:

NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[self.valueSwitch setOn:[[defaults objectForKey:@"truthonoff"] boolValue] animated:YES];
[self.valueSwitch addTarget:self action:@selector(stateSwitched:) forControlEvents:UIControlEventValueChanged];

stateSwitched执行此操作:

-(void)stateSwitched:(id)sender {
    UISwitch *tswitch = (UISwitch *)sender;
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    [defaults setObject: tswitch.isOn ? @"YES" : @"NO" forKey:@"truthonoff"];
    [defaults synchronize];
}

希望这会有所帮助.. :)

答案 1 :(得分:1)

有点太晚了,而不是像你接受的答案那样:

NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject: tswitch.isOn ? @"YES" : @"NO" forKey:@"truthonoff"];
[defaults synchronize];

正确的方法是:

NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setBool:tswitch.isOn forKey:@"truthonoff"];
[defaults synchronize];

这使您无需检查布尔值,因为NSUserDefaults可以获取boolean值。

此外,检索布尔值会更容易:

bool truthonoff = [defaults boolForKey:@"truthonoff"];

boolForKey

上阅读更多内容

答案 2 :(得分:0)

将您的UISwitchIBOutlet中的ViewController相关联 您可以(取消)将开关设置为:

[mySwitch setOn:TRUE animated:TRUE];

Method Reference