Deep copy Shallow copy

Shallow copy

Shallow copy does not copy the object itself, but copies the pointer to the object, but still points to the object that the pointer points to in the same heap memoryCopy the code

You can see that the address of the pointer object in the stack has changed in the shallow copy, but it still points to the same heap addressCopy the code

Deep copy

Copy objects directly to an area of memory, and then point the pointer of the new object to that area of memory.Copy the code

As can be seen from deep copy, the object is directly copied to an area of memory (allocate a new memory space), and then the pointer of the new object points to the memory, the original object and the assigned object do not affect each other.Copy the code

Essential differences between deep copy and shallow copy

It depends on whether new memory space is opened in heap memory.Copy the code

Distinguish between deep and shallow copies

We mainly start with container classes and non-container classes. Both container classes and non-container classes have mutable objects and immutable objects, so they are divided into four types:

  • Non-container immutable object: NSString
  • Non-container-class mutable object: NSMutableString
  • Container class immutable object: NSArray
  • Container class mutable object: NSMutableArray

conclusion

[object copy] : Deep copy for mutable objects and shallow copy for immutable objects. [Object mutableCopy] : It is always a deep copy.Copy the code