1. Simple replication can only implement shallow copy: assign values to the pointer, so that the two pointers point to the same memory space, and the operation is not safe.
2. The foundation class complies with the <nscopying> and <nsmutablecopying> protocols to implement the copy and mutablecopy methods. Therefore, foundation objects can use these methods to create copies or mutable copies of objects.
@ Protocol nscopying
-(ID) copywithzone :( nszone *) zone;
@ End
@ Protocol nsmutablecopying
-(ID) mutablecopywithzone :( nszone *) zone;
@ End
3. If the user-defined class complies with the <nscopying> protocol and <nsmutablecopying> protocol, the copywithzone method and the mutablecopywithzone method must be implemented. Otherwise, the Class Object cannot respond to the copy and mutablecopy messages.
4. Implement the copywithzone method, for example:
-(ID) copywithzone :( nszone *) Zone
{
Student * Stu = [[STUDENT allocwithzone: Zone] initwithname: Self. Name age: Self. Age];
Return Stu;
}
Corresponding to the main function: Suppose there is already a student object stu1;
Then: Student stu2 = [stu1 copy];
Stu2 is a copy of stu1, where deep replication is implemented. stu1 and stu2 correspond to different memory.
5. If your class produces a subclass, The copywithzone: method will also
Inherited
Student * Stu = [[STUDENT allocwithzone: Zone] init];
This method should be changed to: Student * Stu = [[[Self class]
Allocwithzone: Zone] init];
If you compile a copywithzone: Method of a class, the subclass method should first call the copy method of the parent class to copy the inherited copy instance variable.