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).

Sign up to request clarification or add additional context in comments.

1 Comment

Invoking copy on a mutable array will return a new non-mutable array. Invoke mutableCopy instead if you want another mutable array.
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 Comment

do you mean to use initWithArray:copyItems:YES for that second method? As it stands, I believe those two methods are identical.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.