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

Adding object to existing NSMutableArray causes exception

我想向现有 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'

我的代码有什么问题?

What's wrong of my code?

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

要解决此问题,请对您检索的数组调用 mutableCopy

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