How to copy a NSMutableArray

Blane Townsend picture Blane Townsend · Apr 23, 2011 · Viewed 30.5k times · Source

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?

Answer

Regexident picture Regexident · Apr 23, 2011

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.