Copying an object is to copy an object as a copy. It will open up a new memory (heap memory) to store the copy object, just like copying a file, that is, the source object and the copy object are two different memory regions. The <nscopying> protocol or <nsmutablecopying> protocol must be implemented for objects that can be copied: nsnumber, nsstring, nsmutablestring, nsarray, nsmutablearray, nsdictionary, nsmutabledictionary
Copy: the copy of the generated object is unchangeable.
Mutablecopy: The generated object copy is variable.
Shortest copy and deep copy
The copy value copies the object itself. The attributes and contained objects in the object are not copied.
Deep COPY Copies both the object and the attributes of the object.
Classes that support replication in foundation. The default value is light replication.
Custom object copy
The object has the replication feature and must implement the nscopying and nsmutablecopying protocols to implement the Protocol's copywithzone: method or mutablecopywithzone: method.
Shallow copy implementation
-(id)copyWithZone:(NSZone *)zone{ Person *person = [[[self Class]allocWithZone:zone]init]; p.name = _name; p.age = _age; return person; }
Deep copy implementation
-(void)copyWithZone:(NSZone *)zone{ Person *person = [[[self Class]allocWithZone:zone]init]; person.name = [_name copy]; person.age = [_age copy]; return person; }
Relationship between deep copy and retain
Relationship between copy, mutablecopy, and retain
Objects that can be copied in the foundation. When we copy an immutable object, the function is equivalent to retain (memory optimization by cocoa)
When mutablecopy is used, the copy is variable regardless of whether the source object is variable.
When we copy a mutable object, the duplicate is immutable.