I have a question for a newbie
NSMutableArray *_dataArray;
_dataArray=@[
@[@"Image_f",@"aaaaaa"],
@[@"Image_h",@"bbbbbb"],
@[@"Image_r",@"cccccc"],
@[@"Image_s",@"dddddd"],
@[@"Image_r",@"eeeeee"]];
Then I want to replace the element with index 1
NSArray *rpArr = [NSArray arrayWithObjects:@"ggggg_hhhh",@"替换的元素内容", nil];
[_dataArray replaceObjectAtIndex:1 withObject:rpArr];
When I use this method to replace (modify) element 1, I always get an error. How can I fix this?
迷茫2017-05-02 09:32:09
@[]
只能生成不可变的数组,即 NSArray
,而 replaceObjectAtIndex
是 NSMutableArray
才有的方法。
在你的 @[...]
后面调用下 mutableCopy
That’s it.
NSMutableArray *_dataArray = @[...].mutableCopy;
[_dataArray replaceObjectAtIndex:1 withObject:@[...]];
高洛峰2017-05-02 09:32:09
Knowledge point NSArray to NSMutableArray. If your _dataArray is NSMutableArray, you should open up space first. You can only declare it as NSArray and then convert
NSArray* _dataInitArray = @[
@[@"Image_f",@"aaaaa"],
@[@"Image_h",@"bbbbbb"],
@[@"Image_r",@"cccccc"],
@[@"Image_s",@"dddddd"],
@[@"Image_r",@"eeeeee"]
];
NSMutableArray * _dataArray = [_dataInitArray mutableCopy];
NSArray *rpArr = [NSArray arrayWithObjects:@"ggggg_hhhh",@"替换的元素内容", nil];
[_dataArray replaceObjectAtIndex:1 withObject:rpArr];
for(int i = 0 ; i < 5; i++){
NSLog(@"%@",_dataArray[i][1]);
}
2016-09-17 21:53:55.159 Test[3124:369229] aaaaa
2016-09-17 21:53:55.160 Test[3124:369229] Replaced element content
2016-09-17 21:53:55.160 Test[3124:369229] cccccc
2016-09-17 21:53:55.160 Test[3124:369229] dddddd
2016-09-17 21:53:55.160 Test[3124:369229] eeeeee
Program ended with exit code: 0