Understanding the Autorelease of objective-c

Source: Internet
Author: User

For iOS applications, in order to maintain memory efficiency, the system will closely monitor the object's reference count, and when the reference count is 0 o'clock, the object will be released immediately. In general, use release is sufficient: Alloc/copy/new or retain an object, uses the object, and releases the object with release.

But considering this situation, if a method needs to return a new object, and this method is not named Alloc/copy/new, the caller will certainly not use release to balance the reference count of the returned object, and on the other hand, our method cannot use release. Because doing so will immediately release the object and return an empty object

In view of this situation, objective-c designed the autorelease, which can ensure that the object can be released correctly and return valid objects.

It sounds a bit magical, how does it come true?

Good technology, the principle is always simple. The beauty of Autorelease is that it finds a suitable time to release the returned object, which is the time when the message loop ends. We only need to call Autorelease before returning the object, the object is added to the autorelease pool (but does not reduce the object's reference count, so this time the returned object is still valid), and then returns, the program continues execution until the completion of this message loop, Then the temporary objects recorded in the Autorelease pool are respectively release.

In general, the message loop runs once in milliseconds or even microseconds, so the efficiency of the autorelease is still very high 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.