2

我无法保存 NSMutableDictionary。我正在尝试将其保存到 NSUserDefaults,然后加载并更改为蓝色,然后再次保存。

所以我最初是这样写的:

NSMutableDictionary *d = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                              firstNameLbl, @"firstName",
                              lastNameLbl, @"lastName", 
                              nil];
    [[NSUserDefaults standardUserDefaults] setObject:d forKey:@"youDict"];
    [[NSUserDefaults standardUserDefaults] synchronize];

然后我加载它并尝试更改如下值:

NSMutableDictionary *d = [[NSUserDefaults standardUserDefaults] objectForKey:@"youDict"];
    [d setObject:textField.text forKey:key];
    [[NSUserDefaults standardUserDefaults] setObject:d forKey:@"youDict"];
    [[NSUserDefaults standardUserDefaults] synchronize];

但是,这行 ,[d setObject:textField.text forKey:key];导致应用程序崩溃,我收到此错误:

'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'

4

3 回答 3

4

objectForKey 为 NSUserDefaults 返回一个不可变的值。为了完成这项工作,将第二个代码块的第一行替换为:

 NSMutableDictionary *d = [NSMutableDictionary dictionaryWithDictionary: [[NSUserDefaults standardUserDefaults] objectForKey:@"youDict"]];
于 2012-05-05T11:03:37.230 回答
1

尝试使用此代码,我认为我们会对您有所帮助。

 NSMutableDictionary *d = [NSMutableDictionary dictionaryWithDictionary: [[NSUserDefaults standardUserDefaults] ValueForKey:@"youDict"]];
于 2012-05-05T11:10:46.137 回答
1

NSUserDefaults 不区分可变对象和不可变对象,因此当您取回它时,它将是不可变的:

如果你想要一个可变字典,只需使用 mutableCopy:

NSMutableDictionary *d = [[[NSUserDefaults standardUserDefaults] objectForKey:@"youDict"] mutableCopy];

希望对你有帮助...

于 2012-05-05T11:04:04.433 回答