【问题标题】:how to update NSMutableDictionary如何更新 NSMutableDictionary
【发布时间】:2012-02-06 08:06:11
【问题描述】:

我有

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'

我们如何更新字典?

【问题讨论】:

  • 崩溃日志显示您的字典不可变。你能告诉我们你是如何分配/初始化字典的吗?
  • 如果您的@property 中有copy,请将其替换为retainstrong。复制总是创建不可变的对象。

标签: iphone xcode4 nsmutabledictionary


【解决方案1】:

即使我的字典是可变的,我也遇到过同样的异常。
让我向您解释一下我的情况,可能会有所帮助:
我有NSMutableArrayNSMutableDictionary

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

[dict setObject:@"" forKey:@""];

所以我改变了我的代码如下,

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

效果很好:)

【讨论】:

    【解决方案2】:

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

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

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

    他们将其初始化为

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

    解决了异常

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多