深度复制NSArray [英] Deep copying an NSArray
问题描述
有没有任何内置的函数允许我深度复制 NSMutableArray
?
Is there any built-in function that allows me to deep copy an NSMutableArray
?
,有人说 [aMutableArray copyWithZone:nil]
作为深度复制。但我试过,它似乎是一个浅拷贝。
I looked around, some people say [aMutableArray copyWithZone:nil]
works as deep copy. But I tried and it seems to be a shallow copy.
现在我手动做一个为
loop:
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];
}
}
}
}
推荐答案
由于 Apple docs 状态, p>
As the Apple docs state,
如果你只需要一个一级的复制,你可以显式调用一个...
If you only need a one-level-deep copy, you can explicitly call for one...
NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:oldArray copyItems:YES];
上述代码创建一个新数组,其成员是浅拷贝
The above code creates a new array whose members are shallow copies of the members of the old array.
请注意,如果您需要深度复制整个嵌套数据结构 - 链接的Apple文档称为真正的深层副本 - 这种方法是不够的 - 请看这里的其他答案。
Note that if you need to deeply copy an entire nested data structure - what the linked Apple docs call a "true deep copy" - then this approach will not suffice - see the other answers here.
这篇关于深度复制NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!