如何更新NSMutableDictionary

时间:2012-02-06 08:06:11

标签: iphone xcode4 nsmutabledictionary

我有

NSMutableDictionary *mutDic;

它加载了来自其他NSMutableDictionary的一些值 从警报我试图更新其价值

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self.mutDic setValue:[[alertView textFieldAtIndex:0] text] forKey:@"lname"];
}

但是我得到了这个例外

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'

我们如何更新字典?

2 个答案:

答案 0 :(得分:5)

我之前有同样的例外,即使我的字典是可变的。
让我向你解释我的情景,可能会有所帮助:
我有NSMutableArray NSMutableDictionary

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [array objectAtIndex:0];

[dict setObject:@"" forKey:@""];< - 它正在崩溃......

所以我改变了我的代码,

NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:[array objectAtIndex:0]];

它运作良好:)

答案 1 :(得分:0)

发现异常问题,但没有完全解决

在加载时我需要从其他字典中获取值,因为我使用的方法是错误的,我只是将oldDic分配给mutDic,我改为

self.mutDic = [[[NSMutableDictionary alloc] initWithDictionary:manager.oldDic] retain];

他们的初始化

self.oldDic = [[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"F Name",@"fname",@"L Name",@"lname", nil ]retain];

解决了异常