Save and Load UISwitch state

你离开我真会死。 提交于 2019-12-03 14:12:44

问题


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.



来源:https://stackoverflow.com/questions/6662584/save-and-load-uiswitch-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!