Search code examples
iosobjective-cnsuserdefaultsuiswitch

Save switch position after closing app


I wanted to know how to save the position of a switch to close and open the application ?

-(IBAction)switch_poids_passagers:(UISwitch *)sender {

 NSString *poids_passagers_total;
 if(sender.on) {
      poids_passagers_total = @"1";

 } else {
      poids_passagers_total = @"2";

 }

 [[NSUserDefaults standardUserDefaults] setObject:poids_passagers_total forKey:@"poids_passagers_total"];
 [[NSUserDefaults standardUserDefaults] synchronize];

}


Solution

  • NSUserDefaults can save and retrieve BOOLS with a pair methods it provides:

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:self.myUISwitch.on forKey:@"switchValue"];
    // ...
    

    Later on, maybe in viewWillAppear...

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL switchValue = [defaults boolForKey:@"switchValue"];
    self.myUISwitch.on = switchValue;