Louis Holley
Louis Holley

Reputation: 135

How to save the state of a UISwitch to file

A similar question on stackoverflow yielded a combination of:

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

and

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

I've been trying to look into NSUserDefaults, but I understand neither what these pieces of code do, or where they should be in my program.


Could anyone tell me where they need to go? Why doesn't the code below work?

- (void)viewDidLoad
{
    [super viewDidLoad];
    BOOL switchState = [[NSUserDefaults standardUserDefaults]  boolForKey:@"mySwitchValueKey"];
    if (switchState == YES) {
        [hard1ON setOn:TRUE];
    } else {
        [hard1ON setOn:FALSE];
    }
}

- (IBAction)switchValueChanged
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setBool:switchState forKey:@"mySwitchValueKey"];

    if (hard1ON.on) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"theChange" object:nil];
    } else {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"theChange2" object:nil];
    }
}

Upvotes: 0

Views: 154

Answers (2)

Anoop Vaidya
Anoop Vaidya

Reputation: 46543

These two statements are used to create an instance of NSUserDefaults and then setting the switchState in standardUserDefaults, that is with your app.

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

switchState must be declared anywhere above this statement as BOOL switchState.

From this statement BOOL swichState = [userDefaults boolForKey:@"mySwitchValueKey"]; the boolValue is read back into swichState.

The above code should be in the method that is invoked when you change or flip or move to aother view, assuming switchState is an local property to a class.

If it is a global or shared it can be any where, most suitable place would be applicationSholdTerminate:.

Upvotes: 1

Mrunal
Mrunal

Reputation: 14118

  • First two lines are for saving your data, so on any submit/save button event you can use this lines to save your data. Or else you can save each time your switch value changes.
  • Second line is for retrieving your saved data, so you can use this when your application gets re-lauched. So that you can get to know, what data has been saved in last launch. And according to that you can go ahead in your code.

For more details check this link, it might give you brief description about NSUserDefaults.

Hope this helps.

Upvotes: 0

Related Questions