How to copy a NSMutableArray How to copy a NSMutableArray xcode xcode

How to copy a NSMutableArray


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.