Autorelease mechanism explanation

Source: Internet
Author: User
Tags instance method

The autorelease mechanism is a member of iOS memory management. In the MRC, the memory release is delayed by invoking [obj autorelease] , in which we have no need to know autorelease to manage the memory well enough. And in this behind, objective-c help us do what, and how to properly manage the memory, the following we explain the autorelease mechanism, I hope you have a further understanding of Autorelease!!!

when does the Autorelease object release?

I do not know everyone in the interview, have encountered such a problem, I am in the world of the interview experience. If you take the Autorelease object when released to do the interview questions, may be correctly answered not a few, you may be answered, "The current scope is the closing of the curly brace", if this answer, obviously did not correctly understand the autorelease mechanism.

The Autorelease object is not released until the current runloop iteration is complete without manually adding Autorelease pool. The reason for this release is that the system has already joined the auto-release pool push and pop in each runloop iteration.

(Each runloop will create a autoreleasepool and release after the end of the runloop iteration)

Here is a piece of code that describes the use of Arc and MRC Autorelease, as follows:

// MRC NSAutoreleasePool *pool = [NSAutoreleasePool alloc] init]; ID obj = [NSObject alloc] init]; [obj autorelease]; [Pool drain]; // ARC @autoreleasepool {  id obj = [NSObject alloc] init];}

Autorelease's Apple implementation

We can look at the Apple Autorelease implementation through OBJECTIVE-C library RUNTIME/OBJC-ARR.MM.

classAutoreleasepoolpage {StaticInlinevoid*push () {is equivalent to generating or holding a NSAutoreleasePool class object}StaticInlinevoid*pop (void*token)        {Equivalent to discarded NSAutoreleasePool class object Releaseall (); }        StaticInlineIDAutorelease (IDobj) {The AddObject class method equivalent to the NSAutoreleasePool class Autoreleasepoolpage*autoreleasepoolpage =Obtain the Autoreleasepoolpage instance being used; Autoreleasepoolpage-Add (obj); }        ID*add (IDobj) {Append an object to an internal array}voidReleaseall () {Call the Release instance method of the object in the internal array}}; void*objc_autoreleasepoolpush (void)    {        returnautoreleasepoolpage::p ush (); }    voidObjc_autoreleasepoolpop (void*ctxt)    {autoreleasepoolpage::p op (ctxt); }    ID*objc_autorelease (IDobj) {        returnautoreleasepoolpage::autorelease (obj); }

After the iOS program starts, the main thread creates a runloop and creates two observer, which are all in the _wraprunloopwithautoreleasepoolhandler() function.

The first observer listens for Entry(which is about to enter loop), the callback is created in _objc_autoreleasepoolpush () and the priority is highest, ensuring that the release pool is created before all callbacks .

The second observer listener has two events:beforewaiting(entering hibernation) calls _objc_autoreleasepoolpop () and _objc_autoreleasepoolpush () Frees the old release pool and creates a new release pool, andexitLoop calls _objc_autoreleasepoolpop () to release the auto-free pool. This priority is the lowest, ensuring that the release pool is called after all callbacks have occurred.

The above code finds that Autoreleasepoolpage is the core class: The function primarily calls the push and pop methods. Let's look at the Autoreleasepoolpage class together.

Autoreleasepoolpage

Here is the Autoreleasepoolpage class:

# define Empty_pool_placeholder ((ID*)1) # define pool_boundary NilStaticpthread_key_tConstKey =Autorelease_pool_key; Staticuint8_tConstSCRIBBLE =0xa3;//0XA3A3A3A3 after releasing    Staticsize_tConstSIZE =#ifProtect_autoreleasepoolpage_max_size; //must be multiple of VM page size#elsepage_max_size; //size and alignment, power of 2#endif    Staticsize_tConstCOUNT = SIZE/sizeof(ID); magic_tConstMagic; ID*Next; pthread_tConstthread; Autoreleasepoolpage*Constparent; Autoreleasepoolpage*Child ; uint32_tConstdepth; uint32_t Hiwat;

Under Arc, if we use the @autoreleasepool {} to create a autoreleasepool, then the compiler will change to the following:

void *context = objc_autoreleasepoolpush (); // The Code objc_autoreleasepoolpop (context) in {} ;

Autoreleasepoolpage is a class that relies on C + + implementations.

    • Autoreleasepool does not have a separate structure, and is composed of many autoreleasepoolpage in a doubly linked list, with the parent pointing to the previous page, and child pointing to the next page.
    • Each object in the Autoreleasepoolpage will open up the size of a page of virtual memory (that is, 4,096 bytes), except that the instance variable occupies space, and other spaces are used to store the address of the Autorelease object.
    • ID *next points to the next position of the top of the Stack object
    • If the autoreleasepoolpage space is occupied, a autoreleasepoolpage connection list is created, and later objects are added to the new page.

Assuming that the current thread has only one Autoreleasepoolpage object, the memory address of the object is as follows:

As can be seen from the above, when an object sends aautorelease消息,就是将当前这个对象加入到AutoreleasePoolPage的栈顶next指向的位置。

Release time

Each time a Objc_autoreleasepoolpush call is made, the runtime adds the current autoreleasepoolpage to a Sentinel object, which becomes the following structure:

The Objc_autoreleasepoolpush return value is the address of the Sentinel object and is objc_autoreleasepoolpop as a parameter. So:

    1. Find the Sentinel's page based on the incoming Sentinel location
    2. Sends a release message to the Autorelease object inserted later than the Sentinel object, and moves the next pointer to the correct position

The automatic release pool is composed of a autoreleasepoolpage, and the Autoreleasepoolpage is formed by a double-linked list.

When the pop is passed in to the boundary object, then the release message is sent to the object in the page.

The above is the autorelease mechanism of personal understanding, hope to help you!!!

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.