9

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

I would like to have a function which when passed in an NSMutableArray, it takes the array and fills up another array with the content.

Is it as simple as someArray = passedInArray? OR os there some initWith function?

2 Answers 2

14

This should work good enough

[NSMutableArray arrayWithArray:myArray];

Also, copy method probably does the same

[myArray copy];

But simple assignment won't clone anything. Because you assign only a reference (your parameter probably looks like NSMutableArray *myArray, which means myArray is a reference).

1
  • 8
    Invoking copy on a mutable array will return a new non-mutable array. Invoke mutableCopy instead if you want another mutable array.
    – TomSwift
    Aug 15, 2013 at 20:40
5

Don't mind but your question seems to be a duplicate deep-copy-nsmutablearray-in-objective-c; however let me try.

Yeah its not so simple, you have to be somewhat 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];
}

Here is documentation article Copying Collections

1
  • do you mean to use initWithArray:copyItems:YES for that second method? As it stands, I believe those two methods are identical.
    – JaredH
    Jun 20, 2015 at 20:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.