views:

103

answers:

3

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 following:

//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]

+1  A: 

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.

Adam Eberbach
At the end of the operation I want y to be [A,B,C,D,E,F,G,H,I,J]
Sheehan Alam
OK, so do things in the order you showed - but as Jared said, don't leak array Y when you overwrite it. Check with the static analyzer (shift-command-A in Xcode)
Adam Eberbach
A: 

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)

Jared P
but will x = [y copy] make my array [A,B,C,D,E,F,G,H,I,J] or will it be the value of y which is [E,F,G,H,I,J]?
Sheehan Alam
+2  A: 

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).
JeremyP