Save and Load UISwitch state

2019-03-17 00:52发布

问题:

I want to save the swtich state and load it when the program restarted.

[[NSUserDefaults standardUserDefaults] setBool:switchControl.on forKey:@"switch"];
[[NSUserDefaults standardUserDefaults] synchronize];

This is the saving part

BOOL test= [[NSUserDefaults standardUserDefaults] boolForKey:@"switch"];
NSLog(@"%@",test?@"YES":@"NO");
if(test == YES)
    [switchControl setOn:YES animated:YES];
else
     [switchControl setOn:NO animated:YES];

This is the part that is need to be set the switch to its value.I did this in viewdidload method because when i close the application and restarted it i want the state of the switch set the saved part .

But it is still showing the default part can u help me to set it?

回答1:

Did you create the switch as an IBOutlet with properties? If so, I think your problem is that you dont refer to your switchControl as self.switchControl.

Then your correct saving statement will become

[[NSUserDefaults standardUserDefaults] setBool:self.switchControl.on forKey:@"switch"];
[[NSUserDefaults standardUserDefaults] synchronize];

I'd move the part that sets the switch into viewWillAppear and do it like this:

- (void)viewWillAppear:(BOOL)animated
{
  [super viewWillAppear:animated];
  BOOL test= [[NSUserDefaults standardUserDefaults] boolForKey:@"switch"];
  NSLog(@"%@",test?@"YES":@"NO");
  [self.switchControl setOn:test animated:YES];
}

I took out an unnecessary if-statement for you, too.