Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a NSMutableArray

Tags:

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?

like image 433
Blane Townsend Avatar asked Apr 23 '11 19:04

Blane Townsend


People also ask

What is difference between NSArray and NSMutableArray?

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.

What is NSMutableArray?

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 .

What is mutableCopy Objective C?

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.

How do I create an NSArray in Objective C?

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.


1 Answers

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.

like image 55
Regexident Avatar answered Sep 22 '22 08:09

Regexident