views:

65

answers:

2

Hi,
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!

+1  A: 

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];
hotpaw2
And can I use a method without a declaration? I must save the state in a controller and after verify the state and do some action in another controller... How can I do this?
Matthew
That sounds like a new and different question.
hotpaw2
@Matthew: I think that is easy, you can just get the state out of the userDefaults in another view controller. Look at my answer for a simpler answer, without method declaration at all:)
vodkhang
+1  A: 

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

vodkhang
I believe this is what I'm looking for... I'll try... Thanks!
Matthew