-3

I am not able to get understand what is difference between deep copy and shallow copy. Please make me understand with the simple example. Thanks

vikrant tanwar
  • 219
  • 4
  • 15
  • 5
    Please refer this http://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy – Vishnu gondlekar Jan 29 '16 at 19:05
  • 1
    A shallow copy is also known as address copy. In this process, you only copy address not actual data while in the deep copy you copy data. – divya d Aug 22 '17 at 07:12

1 Answers1

6

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 Shallow copy

Deep copy Deep copy

Volodymyr
  • 1,165
  • 5
  • 16