Reputation: 21237
No matter what I do, I cannot get my NSUserDefaults to save when using the iOS simulator. I've read the posts, and I am calling synchronize
, but it's still not working.
I have a button that simulates a check box. When the button is clicked, the method toggleSavedPassword
fires. Even after checking the box (i.e. setting "save_password" to true), when I come back into the app, the value is reset to false every time.
What am I doing wrong? Thanks!
This is my output every time I follow the sequence of launching the app and clicking the checkbox:
password NOT saved
user save password set to: true
password save set
user default didn't save
Here is the code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *userDefaults = [[NSUserDefaults alloc] init];
NSLog([self.userDefaults boolForKey:@"save_password"] ? @"password saved" : @"password NOT saved");
// check the save password box based on user default settings
if ([userDefaults boolForKey:@"save_password"]) {
[self.savePasswordCheckBox setBackgroundImage:[UIImage imageNamed:@"checked_checkbox"] forState:UIControlStateNormal];
}
}
- (IBAction)toggleSavePassword:(UIButton *)sender {
self.savePassword = !self.savePassword;
NSString *temp;
if (self.savePassword) temp = @"true";
else temp = @"false";
NSLog(@"user save password set to: %@\n", temp);
if (self.savePassword) {
[self.savePasswordCheckBox setBackgroundImage:[UIImage imageNamed:@"checked_checkbox"] forState:UIControlStateNormal];
[self.userDefaults setBool:YES forKey:@"save_password"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"password save set");
} else {
[self.savePasswordCheckBox setBackgroundImage:[UIImage imageNamed:@"unchecked_checkbox"] forState:UIControlStateNormal];
[self.userDefaults setBool:NO forKey:@"save_password"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
NSLog([self.userDefaults boolForKey:@"save_password"] ? @"Confirmed" : @"user default didn't save");
}
Upvotes: 0
Views: 918
Reputation: 332
where is your self.userDefaults
-setter
method
BTW, it should be NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
Upvotes: 1
Reputation: 332
No need to add the NSUserDefaults as a property.
You could just use
[NSUserDefaults standardUserDefaults];
For saving:
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"save_password"];
For retrieving:
[[NSUserDefaults standardUserDefaults] boolForKey:@"save_password"];
Upvotes: 2