将对象添加到现有NSMutableArray会导致异常

时间:2015-07-26 17:54:16

标签: ios objective-c cocoa-touch exception nsmutablearray

我想将一个对象添加到已有数据的现有NSMutableArray中。

- (void)viewDidLoad {
    [super viewDidLoad];
    NSDictionary *json = [Server getMsgRecordwithfid:self.fid];
    self.msgRecords = [[NSMutableArray alloc] init];
    self.msgRecords = [json objectForKey:@"msg_record"];
}
- (IBAction)sendBtn:(id)sender {
    NSDictionary *json = [Server insertNewMsg:data];
    [self.msgRecords addObject:json];
}

当我运行上面的代码时,程序在[self.msgRecords addObject:json];崩溃。然后它给出了以下错误消息。

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:2)

  

我的代码有什么问题?

您的代码正在写NSMutableArray,用可从json检索的不可变的替换可变集合。

要解决此问题,请在您检索的阵列上调用mutableCopy

// The first line is no longer necessary
//self.msgRecords = [[NSMutableArray alloc] init];
self.msgRecords = [[json objectForKey:@"msg_record"] mutableCopy];