将新数组插入NSMutableArray

时间:2014-04-20 08:47:49

标签: ios objective-c nsmutablearray

我有一个带AFHTTPRequestOperation的json解析器。

我的解析代码:

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

operation.responseSerializer = [AFJSONResponseSerializer serializer];

我有NSMutableArray

@property (strong, nonatomic) NSMutableArray * myDirectory;

首先,我加载主要10个项目并添加:

self.myDirectory = responseObject;

之后,当我想加载更多10个项目时,我尝试了很多东西,但错误是:

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

我试过了:

[self.myDirectory insertObject:[responseObject mutableCopy] atIndex:[self.myDirectory count]];
[self.myDirectory addObjects:responseObject];
etc...

我必须使用什么?

3 个答案:

答案 0 :(得分:1)

AFNetworking返回不可变数组(NSArray),因此您必须将其指定为:

self.myDirectory = [responseObject mutableCopy]

答案 1 :(得分:0)

你试过[myArray addObjectsFromArray:otherArray];

吗?

答案 2 :(得分:0)

AFNetworking返回不可变数组。所以试试这个:

self.myDirectory = [responseObject mutableCopy];

如果您想将第二个responseObject添加到之前的self.myDirectory,请尝试以下操作:

[self.myDirectory addObjectsFromArray: responseObject];

检查this answer,了解有关copymutableCopy的明确概念。

希望这会有所帮助.. :)

修改

NSArray *arr = [[NSArray alloc] initWithObjects:@"A",@"B", nil];
NSArray *arr1 = [[NSArray alloc] initWithObjects:@"C",@"D", nil];
NSArray *arr2 = [[NSArray alloc] initWithObjects:@"E",@"F", nil];
NSMutableArray *mutableArray= [[NSMutableArray alloc] init];
mutableArray = [arr mutableCopy];
[mutableArray addObjectsFromArray:arr1];
[mutableArray addObjectsFromArray:arr2];
NSLog(@"%@",mutableArray);