Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning/Copying an NSMutableArray in Objective C

Tags:

objective-c

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?

like image 273
some_id Avatar asked Feb 20 '11 15:02

some_id


2 Answers

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

like image 169
Nikita Rybak Avatar answered Nov 08 '22 12:11

Nikita Rybak


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

like image 39
Waqas Raja Avatar answered Nov 08 '22 10:11

Waqas Raja