How to copy a NSMutableArray

31,078

There are multiple ways to do so:

NSArray *newArray = [NSMutableArray arrayWithArray:oldArray];

NSArray *newArray = [[[NSMutableArray alloc] initWithArray:oldArray] autorelease];

NSArray *newArray = [[oldArray mutableCopy] autorelease];

These will all create shallow copies, though.

(Edit: If you're working with ARC, just delete the calls to autorelease.)

For deep copies use this instead:

NSMutableArray *newArray = [[[NSMutableArray alloc] initWithArray:oldArray copyItems:YES] autorelease];

Worth noting: For obvious reasons the latter will require all your array's element objects to implement NSCopying.

Share:
31,078
Blane Townsend
Author by

Blane Townsend

Updated on July 09, 2022

Comments

  • Blane Townsend
    Blane Townsend almost 2 years

    I would simply like to know how to copy a NSMutableArray so that when I change the array, my reference to it doesn't change. How can I copy an array?

  • Supertecnoboff
    Supertecnoboff about 10 years
    What do you mean by shallow and deep copies??
  • Regexident
    Regexident about 10 years
  • Supertecnoboff
    Supertecnoboff about 10 years
    Thanks, very interesting. I never knew about this concepts.
  • Max Strater
    Max Strater about 10 years
    A shallow copy is a new array that contains references to the same elements, a deep copy is a new array that contains copies of each element. If you made a shallow copy and then changed one of the elements in the original array, the shallow copy would also show this change. If it was a deep copy it would not.
  • Matthew Ferguson
    Matthew Ferguson about 7 years
    [sourceArray mutableCopy] with iOS 10 is working great