Is there any built-in function that allows me to deep copy an NSMutableArray?
I looked around, some people say [aMutableArray copyWithZone:nil] works as deep copy. But I tried and it seems to be a shallow copy.
Right now I am manually doing the copy with a for loop:
//deep copy a 9*9 mutable array to a passed-in reference array
-deepMuCopy : (NSMutableArray*) array
toNewArray : (NSMutableArray*) arrayNew {
[arrayNew removeAllObjects];//ensure it's clean
for (int y = 0; y<9; y++) {
[arrayNew addObject:[NSMutableArray new]];
for (int x = 0; x<9; x++) {
[[arrayNew objectAtIndex:y] addObject:[NSMutableArray new]];
NSMutableArray *aDomain = [[array objectAtIndex:y] objectAtIndex:x];
for (int i = 0; i<[aDomain count]; i++) {
//copy object by object
NSNumber* n = [NSNumber numberWithInt:[[aDomain objectAtIndex:i] intValue]];
[[[arrayNew objectAtIndex:y] objectAtIndex:x] addObject:n];
}
}
}
}
but I'd like a cleaner, more succinct solution.
-copyon immutable collections changed between Mac OS X 10.4 and 10.5: developer.apple.com/library/mac/releasenotes/Cocoa/… (scroll down to "Immutable collections and copy behavior")copy, what shall be put into the "deep copy"? If the element is another collection,copydoes not actually yield a copy (of the same class). So I think it's perfectly valid to argue about the type of copy wanted in the specific case.NSCopying/-copy, then it is not copyable— so you should never try to make a copy of it, because that's not a capability it was designed to have. In terms of Cocoa's implementation, non-copyable objects often have some C backend state they're tied to, so hacking a direct-copy of the object could lead to race conditions or worse. So to answer “what shall be put into the ‘deep copy’” — A retained ref. The only thing you can put anywhere when you have a non-NSCopyingobject.