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
.
Author by
Blane Townsend
Updated on July 09, 2022Comments
-
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 about 10 yearsWhat do you mean by shallow and deep copies??
-
Regexident about 10 years@Supertecnoboff: developer.apple.com/library/mac/documentation/Cocoa/Conceptual/…
-
Supertecnoboff about 10 yearsThanks, very interesting. I never knew about this concepts.
-
Max Strater about 10 yearsA 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 about 7 years[sourceArray mutableCopy] with iOS 10 is working great