Problem with replacing elements in OC two-dimensional array?
大家讲道理
大家讲道理 2017-05-02 09:30:09
0
2
887

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?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
迷茫

@[] 只能生成不可变的数组,即 NSArray,而 replaceObjectAtIndexNSMutableArray 才有的方法。
在你的 @[...]后面调用下 mutableCopy That’s it.

NSMutableArray *_dataArray = @[...].mutableCopy;
[_dataArray replaceObjectAtIndex:1 withObject:@[...]];
小葫芦

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template