3
votes

Hi this question got asked before: How do you deep copy a multidimensional NSMutableArray and its contents? but the answer didn't work for me.

I tried:

NSMutableArray *copy = [[NSMutableArray alloc] initWithArray:multiDimArray copyItems:YES];

and:

NSMutableArray *mutableArray = [multiDimArray mutableCopy];
NSMutableArray *copy = [[NSMutableArray alloc] initWithArray:mutableArray copyItems:YES];

The copying works but when I try to replace an object I get the error:

-[__NSArrayI replaceObjectAtIndex:withObject:]: unrecognized selector sent to instance 0x1073b1790

Am I doing anything wrong or is it just not possible to deep copy a multidimensional array without its elements becoming immutable?

Is there a workaround for this?

Thanks

2

2 Answers

0
votes

Try

NSMutableArray *mutableArray = [multiDimArray mutableCopy];

replace with

NSMutableArray *mutableArray = [[NSMutableArray arrayWithArray:multiDimArray] mutableCopy];
0
votes

I got it to work with this:

NSMutableArray *originalArray = [NSMutableArray new];

NSMutableArray *copyArray = [NSMutableArray new];
for(NSArray *subarray in originalArray) {
    NSMutableArray *subCopy = [NSMutableArray new];
    for (id item in subarray){
        [subCopy addObject:[item copy]];
    }
    [copyArray addObject: subCopy];
}

I did it for a two dimensional array. If there are more dimensions you probably have to add an extra for loop for every dimension.