开发者

Confused about copying Arrays in Objective-C

开发者 https://www.devze.com 2023-01-03 03:54 出处:网络
Lets say I have an array X that contains [A,B,C,D,nil]; and I have a second array Y that contains [E,F,G,H,I,J,nil];

Lets say I have an array X that contains [A,B,C,D,nil];

and I have a second array Y that contains [E,F,G,H,I,J,nil];

If I execute the follow开发者_JAVA百科ing:

//Append y to x
[x addObjectsFromArray:y];

//Empty y and copy x
[y removeAllObjects];
y = [x mutableCopy];

What is the value of y? is it?:

[A,B,C,D,E,F,G,H,I,J,nil]

Am I performing the copy correctly?

At the end of the operation I want y to be [A,B,C,D,E,F,G,H,I,J]


At the start:

x is [A, B, C, D] (the nil is not part of the array, it just tells initWithObjects: where the end of the list of objects is). y is [E, F, G, H, I, J]

[x addObjectsFromArray:y]; // only works if x is a mutable array

x is [A, B, C, D, E, F, G, H, I, J]

y is [E, F, G, H, I, J]

[y removeAllObjects]; // only works if y is a mutable array.

x is [A, B, C, D, E, F, G, H, I, J]

y is []

y = [x mutableCopy];

x is [A, B, C, D, E, F, G, H, I, J]

y is [A, B, C, D, E, F, G, H, I, J]

Note that the previous version of y that you emptied may have leaked because you overwrote the pointer with a pointer to a new mutable copy of x. You should have done:

[y release];
y = [x mutableCopy];

Or if you obtained y by using +arrayWithObjects: instead of +alloc followed by -initWithObjects: simply

y = [x mutableCopy]; // release not necessary because you didn't own y (you do now though).


Your arrays are initialised using arrayWithObjects I guess, using those examples - you can't put a nil in an array.

Array X will be [A,B,C,D,E,F,G,H,I,J] with count of 10.

Array Y must be a NSMutableArray (since you are returning a mutable copy) containing the above (if you are talking about using X after the addObjectsFromArray) or it will contain [A, B, C, D] if you mean this as a completely separate example.


Not exactly -- you're appending the objects to x (seems like you understand this) then removing all of the objects from y (seems like you get the idea) except for that y is not now nil, but is an empty array. When you y = [x mutableCopy]; you leak the object formerly at y, and y now points to a new copy of the object x. While this is all valid code, (except for leaking y) its weird, and if you just want to copy the array, all you need to do is x = [y copy];. Also of note, arrays don't actually contain nil at the end (if they do it's not visible to you, the programmer, as part of the API)

0

精彩评论

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