深拷贝与浅拷贝

来源:互联网 发布:廊坊市网络招聘 编辑:程序博客网 时间:2024/06/15 00:13

今天经高人指点,对这个深拷贝和浅拷贝有了新的认知,原来以前理解的都是错的!忘掉以前的一切,让我们重新认识一下深拷贝和浅拷贝。

官方文档在此为证!
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.

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.
A deep copy duplicates the compound object as well as the contents of all of its contained objects.

对于不可变字符串没有复制一说,复制就是浪费,因为他不可变啊,你要用直接给你引用就好了。对于可变的字符串,只有可变和不可变复制之分,也就是你想要一份一样内容但是不可变的,那就用copy,如果你也想来一个可变的一样内容的字符串,那就用mutableCopy。

所以铭记,对于字符串而言,根本没有深浅拷贝之说,深浅拷贝是针对容器而言的!

下面我们正式进入深浅拷贝。

浅拷贝,如文档所说,创建了一个新的容器,然后继续共享原容器的内容,也就是对原内容进行指针拷贝。

深拷贝,创建一个新的容器,并且把原容器中的内容挨个拷贝一下。这才是深拷贝!

你可能会问,那这样算什么

NSMutableArray *originalArray = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", nil];NSMutableArray *mutableCopiedArray = [array mutableCopy];

这个你要注意一下,数组里面的元素是不可变字符串,本来就是不可变的,没有什么意义。

NSMutableArray *array = [NSMutableArray arrayWithObject:@1];NSMutableArray *copiedArray = [NSMutableArray arrayWithObject:array];id mutableCopyArray = [copiedArray mutableCopy];[array addObject:@2];NSLog(@"%@ , %@", array, mutableCopyArray);

看看这个��,里面的元素是一个数组,那么你猜一下,如果我改变array,会不会影响到mutableCopyArray啊,让我来告诉你,绝对会!!!因为它是浅拷贝 !!!!

0 0