应用程序崩溃:将变化方法发送到不可变对象 [英] App Crashing: Mutating method sent to immutable object

查看:163
本文介绍了应用程序崩溃:将变化方法发送到不可变对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图添加一个对象到 NSMutableArray 。最初,我将一些响应数据分配给数组,并可以在表视图中显示它。加载更多的数据后,似乎是在尝试添加新的信息到我的原始数组时崩溃。



我使用AFNetworking为此:

  [operation setCompletionBlockWithSuccess: ^(AFHTTPRequestOperation * operation,id responseObject){

if(!_ myArray){
_myArray = [responseObject objectForKey:@data];
}
else {
[_myArray addObject:[responseObject objectForKey:@data]];
}
[self.tableView reloadData];
}

我得到的错误如下



***由于未捕获异常而终止应用程序'NSInternalInconsistencyException',
原因:' - [__ NSCFArray insertObject:atIndex:]:mutating方法发送到immutable对象'

任何人都可以帮助这个?

responseObject 字典中检索的对象很可能不是 NSMutableArray code>,但是一个(不可变的) NSArray 。您必须创建一个可变的副本才能更改它:

  // ... 
if _myArray){
_myArray = [[responseObject objectForKey:@data] mutableCopy];
}
// ...


I am trying to add an object to an NSMutableArray. Initially I assign some response data to the array, and can display it in a table view. After loading more data, it seems to be crashing when trying to add the new information to my original array.

I am using AFNetworking for this:

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    if(!_myArray){
        _myArray = [responseObject objectForKey:@"data"];
    }
    else{
        [_myArray addObject:[responseObject objectForKey:@"data"]];
    }
    [self.tableView reloadData];
}

The error I am getting is as follows

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

Can anybody help out with this?

解决方案

The object you're retrieving from the responseObject dictionary is most likely not an NSMutableArray, but an (immutable) NSArray. You have to create a mutable copy to be able to change it:

//...
if (!_myArray) {
    _myArray = [[responseObject objectForKey:@"data"] mutableCopy];
}
//...

这篇关于应用程序崩溃:将变化方法发送到不可变对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆