开发者

changing array elements after shallow copying the array

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 ?


You have two different Arrays. That's the answer :).

In detail:

  • arr1 and arr2 are different
  • the elements inside them are pointer to the same objects

When replacing the first object of arr2, you dont overwrite the previous object. And because both array are not the same (only the elements were), the replacement only takes place for arr2 and not arr1.

Again, more detailed:

You need to understand what an array is. They are only a list of pointers to objects. When creating an array with 3 objects, you have an array with 3 pointers to the 3 objects. When you create a copy of that array, you don't create a copy of the objects, but a copy of the 3 pointers. So your arr2 will be a different object with its own 3 pointers pointing to the 3 elements (obj1.. obj3). Now, when you do replaceObjectAtIndex:withObject you only exchange the pointer of arr2 with another one (pointing to another obj (mStr). Because both arrays (arr1 and arr2) are not the same objects (you created a copy), this will only affect arr2 (again: you only changed the pointer of arr2 - you did not change obj1 at all!!).

When you write [obj1 appendString:@"changed"] this will affect both arrays, because both are pointing to obj1.

Hope this makes it more clear for you!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜