objective-c - 深拷贝一个 NSArray

是否有任何内置函数可以让我深度复制 NSMutableArray

我环顾四周,有人说 [aMutableArray copyWithZone:nil] 可以作为深拷贝。但是我试过了,好像是浅拷贝。

现在我正在使用 for 循环手动进行复制:

//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 documentation about deep copies明确指出:

If you only need a one-level-deep copy:

NSMutableArray *newArray = [[NSMutableArray alloc] 
                             initWithArray:oldArray copyItems:YES];

上面的代码创建了一个新数组,它的成员是旧数组成员的浅拷贝。

请注意,如果您需要深度复制整个嵌套数据结构(链接的 Apple 文档称为 真正的深度复制),那么这种方法将不够用。请在此处查看其他答案。

https://stackoverflow.com/questions/647260/

相关文章:

objective-c - 允许与另一个 UIView 下的 UIView 交互

ios - UIActionSheet 取消按钮的奇怪行为

iphone - 如何在 UITableView beginUpdates/endUpdates 上

iphone - 如何使 UIView 的 subview 居中

objective-c - 检查当前线程是否是主线程

iphone - cocoa 应用程序的 info plist 中的 "bundle display

ios - 以编程方式获取导航栏的高度

objective-c - "Auto Layout still required after ex

objective-c - 如何在 Objective-C 中执行回调

objective-c - NSLog 覆盖描述方法中对象的内存地址