in Programming in Objective C2 book (Stephen Kochan), there was the following array:
NSMutableArray *arr1 = [NSMutableArray arrayWithObjects:
@"one, @"two", @"three", nil];
and another array declared as follows:
NSMutableArray *arr2;
and a shallow mutable copy takes place as follows:
arr2 = [arr1 mutableCopy];
according to textbook, arr2 now holds a new array but with object references to arr1 objects not real copies for objects in the array.
the book says, to change the first element of arr2 without affecting arr1's first element, write the following lines:
NSMutableString *mStr = [NSMutableString stringWithString:[arr2 objectAtIndex:0]];
[mStr appendString: @"ONE"];
[arr2 replaceObjectAtIndex: 0 withObject: mStr];
can anyone explain why the the first element of arr2 only affected but not the first element of arr1 too ?
mStris a whole new object. Before-replaceObjectAtIndex:withObject:, it didn’t exist in eitherarr1orarr2, and the object at index 0 was in fact the same object in both arrays. You haven’t simply changed the object at index 0 (which would affect both arrays) — you’ve replaced it inarray2with an entirely new object.