Copy, mutablecopy, shap copy, and deep copy of objects in objective-C

Source: Internet
Author: User

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.

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.