设置值NSMutableDictionary?

时间:2012-05-05 10:58:15

标签: iphone objective-c ios ipad nsmutabledictionary

我在保存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'

3 个答案:

答案 0 :(得分:4)

objectForKey返回NSUserDefaults的不可变值。要使这项工作替换第二个代码块的第一行:

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

答案 1 :(得分:1)

NSUserDefaults不区分可变对象和不可变对象,所以当你找回它时它将是不可变的:

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

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

希望,这会对你有帮助......

答案 2 :(得分:1)

尝试使用此代码我认为我们会为您提供帮助。

 NSMutableDictionary *d = [NSMutableDictionary dictionaryWithDictionary: [[NSUserDefaults standardUserDefaults] ValueForKey:@"youDict"]];