Copying an NSMutableArray using mutableCopy apparently creates a physical new copy of the array. The evidence of this is that removal of an element from the copy using removeObjectAtIndex does not remove the element from the original. However if an element in the copy is changed, the element in the original is also changed. This is about as intuitive as a photon of light being both a particle and a wave and I do not understand it. Please can someone explain this to me.
Code follows.
NSMutableArray *dataArray = [NSMutableArray arrayWithObjects:
[NSMutableString stringWithString:@"one"],
[NSMutableString stringWithString:@"two"],
[NSMutableString stringWithString:@"three"],
[NSMutableString stringWithString:@"four"],
nil];
NSMutableArray *dataArray2;
NSMutableString *mstr;
dataArray2 = [dataArray mutableCopy];
[dataArray2 removeObjectAtIndex:0];
mstr = [dataArray2 objectAtIndex:0];
[mstr appendString:@"ONE"];
NSLog(@"Data Array: ");
for (NSString *elem in dataArray) {
NSLog(@"%@",elem);
}
NSLog(@"Data Array2: ");
for (NSString *elem in dataArray2) {
NSLog(@"%@",elem);
}
The
mutableCopymethod creates a shallow copy of the array, meaning that references to elements of the original array are copied to the new instance ofNSMutableArrayreturned bymutableCopy. That is why manipulating (adding/removing elements) the copy of the array does not alter the composition of the original array, while changes to elements of the array that allow mutation become “visible” through both copies of the array.