Understanding the autorelease of objective-C

Source: Internet
Author: User

For IOS applications, the system strictly monitors the reference count of objects to ensure memory usage efficiency. When the reference count is 0, the objects are immediately released. Generally, it is enough to use release: alloc/copy/new or retain an object, use the object, and then release the object with release.

 

However, in this case, if a method needs to return a new object, this method is not named after alloc/copy/new, therefore, the caller will certainly not use release to balance the reference count of the returned object. On the other hand, our method cannot use release, because this will immediately release the object and return an empty object.

 

In this case, objective-C designed autorelease to ensure that objects can be correctly released and valid objects can be returned.

 

It sounds amazing. How is it implemented?

 

Good technology is always simple in principle. The beauty of autorelease is that it finds a suitable time to release the returned object, which is the end of the message loop. We only need to call autorelease before returning the object, and the object is added to the autorelease pool (but the reference count of the object is not reduced, so the returned object is still valid at this time), and then return, the program continues to execute until the message loop is completed, and then the temporary objects recorded in the autorelease pool are individually release.

 

Generally, a message runs cyclically in milliseconds or even microseconds. Therefore, autorelease is still very efficient and is indeed a clever design.

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.