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?
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With