NSUserDefault不保存在模拟器中

时间:2014-01-02 02:51:20

标签: ios ios-simulator nsuserdefaults

无论我做什么,在使用iOS模拟器时都无法保存我的NSUserDefaults。我已经阅读了这些帖子,我正在呼叫synchronize,但它仍然无效。

我有一个模拟复选框的按钮。单击该按钮时,方法toggleSavedPassword将触发。即使在选中该框后(即将“save_password”设置为true),当我回到应用程序时,每次都会将值重置为false。

我做错了什么?谢谢!

每次我按照启动应用程序的顺序并单击复选框时,这是我的输出:

password NOT saved
user save password set to: true
password save set
user default didn't save

以下是代码:

- (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");

}

2 个答案:

答案 0 :(得分:2)

无需将NSUserDefaults添加为属性。

你可以使用

[NSUserDefaults standardUserDefaults];

保存:

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"save_password"];

用于检索:

[[NSUserDefaults standardUserDefaults] boolForKey:@"save_password"];

答案 1 :(得分:1)

您的self.userDefaults -setter方法在哪里 顺便说一句,它应该是NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];