Difference between deep copy and shallow copy
This question already has an answer here:
So example we have class
@interface myClass : NSObject
@property (strong, nonatomic) NSObject *reference;
@end
Lets look firstly in shallow copy (standard used in iOS)
myClass *instance = [myClass new];
myClass *copy = [instance copy];
"copy" variable will have copied reference "reference" but both references from both variables ("copy" and "instance") will be pointing to one(same) memory object - what means changing "reference" in one instance will lead to change in another(same for both of them), but if we will reallocate ( copy.reference = [NSObject new]
) it will reallocate only for "copy" variable and for "instance" it will be the previous one.
So all together - copying only references but not the memory they are pointing on (it will be the same for both references)
Deep copy behaving in other way - if you are copying objects it will copy references and each copied reference will be pointing to its own copied memory object. That means changing one object won't lead to changing another as they are copied with references(not like previous one) and are briefly allocated separately in memory.
So all together - copying objects will lead to copy references and objects they are pointing on. Thats why it is deep copy - it copies all and not only references.
Above I added images of shallow and deep copy for better understanding. First is shallow and second is deep.
Shallow copy
Deep copy
链接地址: http://www.djcxy.com/p/79352.html上一篇: 深刻的拷贝和浅拷贝
下一篇: 深拷贝和浅拷贝之间的区别