Cloning / Copying NSMutableArray in Objective-C

How are arrays cloned or copied to other arrays in Objective-C?

I would like to have a function that, when passed to NSMutableArray, takes an array and populates another array with content.

Is it as simple as someArray = passInArray? OR os have some initWith function?

+7
source share
2 answers

That should work well enough

[NSMutableArray arrayWithArray:myArray]; 

In addition, the copy method probably does the same.

 [myArray copy]; 

But a simple assignment will not clone anything. Since you only assign the link (your parameter probably looks like NSMutableArray *myArray , which means myArray is the link).

+11
source

Do not mind, but your question looks like a duplicate of deep-copy-nsmutablearray-in-objective-c ; however let me try.

Yes, it’s not so easy, you have to be a little more careful

 /// will return a reference to myArray, but not a copy /// removing any object from myArray will also effect the array returned by this function -(NSMutableArray) cloneArray: (NSMutableArray *) myArray { return [NSMutableArray arrayWithArray: myArray]; } /// will clone the myArray -(NSMutableArray) cloneArray: (NSMutableArray *) myArray { return [[NSMutableArray alloc] initWithArray: myArray]; } 

Below is the documentation Copying Collections

+5
source

All Articles