0

apologies if this has been asked multiple times but I haven't managed to find an answer.

If I have an NSArray called array1, is there any difference between these 2 methods:

NSArray *array2 = [NSArray alloc] initWithArray:array1];

and:

NSArray * array2 = array1;

Thanks

1 Answer 1

2

Yes.

The first creates a new array.

Te seconds creates a new reference to the original array.

Sign up to request clarification or add additional context in comments.

5 Comments

Wouldn't the first only be a copy of the array only if the copyItems:YES was set?
@chancea It is a copy of the array, because of the 'alloc'. It is not a copy of the items in the original array.
@MarcosCrispino so the first method - if array1 was changed, array2 would still be the original array. The second method - they would both change?
@mrcurious array1 cannot be changed, because it is immutable. You could change the contents of one of the objects in the array (not the reference), and then you would be changing the object in both arrays, because objects stored in the original array are not copied into the second. Anyway, alloc-ing an array creates a new structure in memory with enough room to store all the references as needed. Assigning an existing array to a new variable just needs the pointer, not the storage.
@MarcosCrispino Ok Thanks that makes sense. In general are there situations where one would use the first method over the second? For example setting a public NSArray object declared in your .h file to equal a local NSArray object in a method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.