iOS deep copy and shallow copy

Source: Internet
Author: User

1. Copy keywords

1> shallow copy and deep copy

A shallow copy is a copy of the memory address, so that the target object pointer and source object point to the same piece of memory space.

Deep copy refers to the specific contents of the Copy object, and the memory address is self-allocated, after the end of the copy, two objects, although the value is the same, but the memory address is not the same, two objects do not affect each other, non-interference.

2> Copy and Mutablecopy

Copy: The reference count does not change for a deep copy of a mutable object, and for an immutable object is a shallow copy, the reference count is added one at a time. Always returns an immutable object.

Mutablecopy: Always deep copy, reference count does not change. Always returns a Mutable object.

3> implementation of custom class copy

Steps:

1. Import <NSCopying> Agreement

2. Implement Copywithzone method

3. [Object Copy]

Note: When you include other object pointers in your custom object, you should consider the problem of deep copy and shallow copy

Example:

-(ID) Copywithzone: (Nullable Nszone *) Zone {

person * p = [[Person alloc] init];

P.age = _age;

P.name = _name;//Shallow copy

P.dog = [_dog copy];//deep Copy

return p;

}

Why does 4> use copy to decorate NSString instead of strong?

Because the parent pointer can point to a subclass object, the purpose of using copy is to make the properties of this object unaffected by the outside world, and by using copy, whether I pass in a mutable object or a non-object, I am holding an immutable copy, if we use it as strong, Then this property may point to a mutable object, and if the Mutable object is modified externally, it will affect the property.

iOS deep copy and shallow copy

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.