如何使用 NSUserDefaults 正确保存字段?

How to save fields correctly with NSUserDefaults?

我正在创建一个程序,用于保存来自一个文本字段的字符串和来自第二个文本字段的整数。我正在尝试使用 NSUserDefaults,但当我 运行 程序时,我似乎无法让它们中的任何一个正确保存。当我在处理 NSUserDefaults 时按下带有断点的保存按钮时,它崩溃了。难道我做错了什么?我浏览了文档,但没有帮助。我什至可以使用 2 个不同的 NSUserDefaults 实例吗?

- (IBAction)save:(id)sender {
    //Save stuff fropm textfields
    NSString* name = _nameText.text;
    int count = [_countText.text intValue];

    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    [[NSUserDefaults standardUserDefaults] setObject:name forKey:@"name"];
    [[NSUserDefaults standardUserDefaults] setInteger:count forKey:@"count"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


- (IBAction)load:(id)sender {
    //Load stuff from NSUserDefaults
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    NSString* loadstring = [defaults objectForKey:@"name"];
    _nameText.text =  loadstring;

    NSUserDefaults* defaults2 = [NSUserDefaults standardUserDefaults];
    NSInteger loadint = [defaults2 integerForKey:@"count"];
    _countText.text = [NSString stringWithFormat:@"%li", (long)loadint];
}

在您的 viewDidLoad 中声明 defaults = [NSUserDefaults standardDefaults];(并在 .h 中声明 NSUserDefaults* defaults;)并使用此代码:

- (IBAction)save:(id)sender {
    //Save stuff fropm textfields
    NSString* name = _nameText.text;
    int count = [_countText.text intValue];

    [defaults setObject:name forKey:@"name"];
    [defaults setInteger:count forKey:@"count"];
    [defaults synchronize];
}


- (IBAction)load:(id)sender {
    //Load stuff from NSUserDefaults
    _nameText.text =  [defaults stringForKey:@"name"];
    _countText.text = [NSString stringWithFormat:@"%li", (long)[defaults integerForKey:@"count"]];
}