Question

Is there a method to store the state of a UISwitch with NSUserDefaults?
If the state is ON I'd like to set some action...

Can I do this?
Thanks!

Was it helpful?

Solution

The answer of hotpaw2 is good and can also work well for big segmented control (more than 2 states). But if you only want to store 2 states, why not just use [setBool:forKey:] like this

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
   [userDefaults setBool:switchState forKey:@"mySwitchValueKey"];

and get it out:

   BOOL swichState = [userDefaults boolForKey:@"mySwitchValueKey"];

which imo, is much much simpler, no if else code at all, no string converting back and for

OTHER TIPS

To save:

- (void)mySwitchAction:(id)sender
{
  if (sender == mySwitch) {
    BOOL mySwitchValue = [ sender isOn ];
    NSString *tmpString = mySwitchValue ? @"1" : @"-1" ;
    NSUserDefaults  *myNSUD = [NSUserDefaults standardUserDefaults];
    [ myNSUD setObject:tmpString forKey: @"mySwitchValueKey" ];
    [ myNSUD synchronize ];
    // do other stuff/actions
  }
}

To initialize from saved state:

NSUserDefaults  *myNSUD = [NSUserDefaults standardUserDefaults];
NSString *tmpString =  [ myNSUD stringForKey: @"mySwitchValueKey"];
BOOL mySwitchValue = NO;  // or DEFAULT_VALUE
if (tmpString != nil) { 
  mySwitchValue = ( [ tmpString intValue ] == 1 ); 
}
[mySwitch setOn: mySwitchValue];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top