iOS中关于深拷贝和浅拷贝的理解

2017-08-18  本文已影响0人  freemanIT

在以前的理解当中 copymutableCopy 对应的解释分别是 深拷贝浅拷贝, 但是这样的理解是不对的, 在查找资料后, 理解如下:

所有系统容器类的copy或mutableCopy方法,都是浅拷贝

系统的容器类包括 比如NSArray,NSMutableArray,NSDictionary,NSMutableDictionary 等.

但是很多文章, 或者视频教学里的讲解并非如此. 然而在找资料的过程当中, 我看到了这一段官方的文档

There are two kinds of object copying: shallow copies and deep copies. The normal copy
is a shallow copy that produces a new collection that
shares ownership of the objects with the original. Deep copies create new objects from the originals and add those to the new collection.

大概理解一下

有两种类型的对象拷贝,浅拷贝和深拷贝。正常的拷贝,生成一个新的容器,但却是和原来的容器共用内部的元素,这叫做浅拷贝。深拷贝不仅生成新的容器,还生成了新的内部元素。

In the case of these objects, a shallow copy means that a new collection object is created,
but the contents of the original collection are not duplicated—only the object references are copied to the new container.

以上两段解释意思基本一致

代码可自行验证

NSStringNSMutableString 这两个并不是容器类, 所以谈不上 深拷贝浅拷贝

如果要实现深拷贝, 则用系统方法:
initWithArray:copyItems:

比如:
NSArray *deepCopyArray = [[NSArray alloc] initWithArray:someArray copyItems:YES];

当然可以自定义方法

- (NSArray *)test_deepCopy {
    NSMutableArray *array = [NSMutableArray array];
    for (id element in self) {
        id copyElement = nil;
        if ([element respondsToSelector:@selector(test_deepCopy)]) {
            copyElement = [element test_deepCopy];
        }
        else if ([element respondsToSelector:@selector(copyWithZone:)]) {;
            copyElement = [element copy];
        }
        else {
            copyElement = element;
        }
        [array addObject:copyElement];
    }
    NSArray *result = [NSArray arrayWithArray:array];
    return result;
}

- (NSMutableArray *)test_mutableDeepCopy {
    NSMutableArray *array = [NSMutableArray array];
    for (id element in self) {
        id copyElement = nil;
        if ([element respondsToSelector:@selector(test_mutableDeepCopy)]) {
            copyElement = [element test_mutableDeepCopy];
        }
        else if ([element respondsToSelector:@selector(mutableCopyWithZone:)]) {
            copyElement = [element mutableCopy];
        }
        else if ([element respondsToSelector:@selector(copyWithZone:)]) {
            copyElement = [element copy];
        }
        else {
            copyElement = element;
        }
        [array addObject:copyElement];
    }
    return array;
}

总结:
所有系统容器类的copy或mutableCopy方法,都是浅拷贝
系统的容器类包括

参考博客

上一篇下一篇

猜你喜欢

热点阅读