문제

I have managed to change the state of my UISwitch and save to NSUserDefaults.

My UISwitch is in a different view from the main view and when I flip between views, my UISwitch button always appears ON even though the state may be OFF.

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

And this is how I'm loading the button in the second view controller:

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

How can I ensure the UISwitch state represents the value in the NSUserDefaults (i.e. when it's OFF it shows as OFF and when ON shows as ON)?

도움이 되었습니까?

해결책

Try this:

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

In stateSwitched do this:

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

Hope this helps .. :)

다른 팁

A little too late but Instead of doing like the answer you have accepted:

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

the right way would be:

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

This save you from checking the value of the boolean, since NSUserDefaults can take boolean value.

Also it would be easier to retrieve the boolean:

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

Read up some more on boolForKey

Connect your your UISwitch to an IBOutlet in your ViewController.
You can (un-)set the switch with:

[mySwitch setOn:TRUE animated:TRUE];

Method Reference

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top