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?
The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.
The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray .
The mutableCopy method returns the object created by implementing NSMutableCopying protocol's mutableCopyWithZone: By sending: NSString* myString; NSMutableString* newString = [myString mutableCopy]; The return value WILL be mutable.
Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With