user1268135
user1268135

Reputation: 57

How to save the button state using NSUserDefaults

I am new to iphone.I have small doubt that is I have a button with name Sync off when we click that button the below action executes :

- (IBAction)syncOffClickedInRegisterUserScreen:(id)sender {
    if ([syncOnorOff.titleLabel.text isEqualToString:@"Sync off"]) {
        [syncOnorOff setTitle:@"Sync on" forState:UIControlStateNormal];
    } 
    else {
        [syncOnorOff setTitle:@"Sync off" forState:UIControlStateNormal];
    }
}

Due to the above code, when I click the button the title alternates.

How can I save the state of the button with different titles using NSUserDefaults. If anybody knows this please help me....

Upvotes: 1

Views: 1176

Answers (2)

Matheus Rohwedder
Matheus Rohwedder

Reputation: 13

UIButton *button;

// get nsuserdefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// save selected state
[defaults setBool:button.selected forKey:@"myButtonState"];

Then later, after the app launches again...

// restore the selected state
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
button.selected = [defaults boolForKey:@"myButtonState"];

Upvotes: 0

Damien Locque
Damien Locque

Reputation: 1809

You need to define a key to save this button example :

 #define KEYSTATE @"key.syncState"

and in your function :

-  (IBAction)syncOffClickedInRegisterUserScreen:(id)sender {

    // Get User Defaults
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

    if ([syncOnorOff.titleLabel.text isEqualToString:@"Sync off"]) {
        [prefs setBool:NO forKey:KEYSTATE];
        [syncOnorOff setTitle:@"Sync on" forState:UIControlStateNormal];
    } 
    else {
        [prefs setBool:YES forKey:KEYSTATE];
        [syncOnorOff setTitle:@"Sync off" forState:UIControlStateNormal];
    }

    // save 
    [prefs synchronize];
}

and then you can get the bool (in viewDidLoad: for example) to set the button like this :

if ([[NSUserDefaults standardUserDefaults] boolForKey:KEYSTATE]) {
    // Set ON
}
else {
    // Set OFF
}

Upvotes: 4

Related Questions