NSUserDefaults拒绝存储NSString对象

时间:2013-11-17 18:45:04

标签: ios objective-c nsuserdefaults

我试图在包装类中隐藏我的设置,因此可以通过属性读取和设置配置。但由于未知原因,以下setter不会按预期保存值:

- (void)setCountryCode:(NSString *)countryCode
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (countryCode) {
        [defaults setObject:@"CountryCode" forKey:countryCode];
    } else {
        [defaults removeObjectForKey:@"CountryCode"];
    }
    if (![defaults synchronize]) {
        ALog(@"Something unexpected went wrong. Wasn't able to save CountryCode to NSUserDefaults!"); // Never logged, since there doesn't seem to be an error.
    }
    _countryCode = countryCode;
}

但是在尝试恢复它时,它总是会检索nil

- (id)init
{
    self = [super init];
    if (self) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        _countryCode = [defaults objectForKey:@"CountryCode"];
    }
    return self;
}

我做错了什么?

2 个答案:

答案 0 :(得分:3)

而不是:

[defaults setObject:@"CountryCode" forKey:countryCode];

我想你想这样做:

[defaults setObject:countryCode forKey:@"CountryCode"];

答案 1 :(得分:1)

您正在切换setObject:forKey:中的参数。尝试:

[defaults setObject:countryCode forKey:@"CountryCode"];