Objective-C deep replication and protocols

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.