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?

some_id
  • 29,466
  • 62
  • 182
  • 304

2 Answers2

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

Nikita Rybak
  • 67,365
  • 22
  • 157
  • 181
  • 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 '13 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

Community
  • 1
  • 1
Waqas Raja
  • 10,802
  • 4
  • 33
  • 38
  • 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 '15 at 20:49