Differences between assign, retain, and copy

Source: Internet
Author: User

I. assign attributes

When the data type is int, float, or other native types, you can use assign. Otherwise, memory leakage may occur. For example, if you use malloc to allocate a piece of memory and assign its address to pointer a, If you want pointer B to share the block of memory, then assign a value to assgin B. Assgin is used, and a and B point to the same memory. But now the problem arises. Can a be released directly when a no longer needs this memory? Certainly not, because a does not know whether B is still using this memory. If a is released, B will cause the program to crash when using this memory.

Ii. retain attributes

The retain attribute is proposed to solve the above problem. It uses reference counting. In the above example, we set a reference count for the memory, when the memory is allocated and assigned to a, the reference count is 1. when a is assigned to B, the reference count is increased to 2. if a no longer uses this memory, it only needs to reduce the reference count by 1, indicating that it no longer owns this memory. When B no longer uses this memory, it also reduces the reference count by 1. When the reference count is changed to 0, it means that the memory is no longer referenced by any pointer, and the system can directly release it. In this case, the system automatically calls the dealloc function, and the memory is recycled.

Iii. copy attributes

Copy is used when you do not want a and B to share a piece of memory. A and B each have their own memory. For more information, see the next 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.