removeAllObjects崩溃应用程序

Kru*_*nal 2 iphone objective-c nsarray ipad ios

我想清除我的阵列,我做的是,

我在我的应用程序中有tableview视图,首先我从服务器获取数据并将其加载到tableView中.

-(void)viewDidLoad{

  //fetching data from server using background thread and storing it in array called (msg_array)
  [table reloadData];

}
Run Code Online (Sandbox Code Playgroud)

当最后一行出现在屏幕上时,我想从服务器获取新数据,我想显示它,

-(void)LoadMoreData{ //this method gets fire when last cell is on screen 

    if ([msg_array count]>0) 
    {
        [msg_array removeAllObjects];  //crashes here
    }

}
Run Code Online (Sandbox Code Playgroud)

这给出了错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[__NSArrayI removeAllObjects]: unrecognized selector sent to instance
Run Code Online (Sandbox Code Playgroud)

为什么会导致崩溃:

数组的分配方式如下:

msg_array = [dictShow copy];
Run Code Online (Sandbox Code Playgroud)

dictshow包含数据并将其复制到msg_array,而dictshow是mutabledictionary

(摘自评论)

Wai*_*ain 7

' - [__ NSArrayI removeAllObjects]:发送到实例的无法识别的选择器

这意味着数组没有你试图调用的方法.那是因为它是一个不可变的数组(NSArray),而不是mutable(NSMutableArray).

如果你想改变它,要么使它变得可变.或者,替换:

[msg_array removeAllObjects];
Run Code Online (Sandbox Code Playgroud)

有:

msg_array = @[];
Run Code Online (Sandbox Code Playgroud)

根据您的评论,数组应该是可变的.这意味着你有一个可变的属性/实例变量,但是你要创建一个不可变的实例来存储它.找到该位置并更新它(mutableCopy至少创建/返回).

  • 复制]返回NSArray,这是你的问题.用mutableCopy替换它]. (2认同)