objective-cmemory-managementruntimeautorelease

Objective C autorelease at RUNTIME level


This is not a duplicate of a thread in that link, because my question is related to RUNTIME calls, NOT how autoreleasepool{} block works or why it is needed. I was asking what is the call stack of RUNTIME functions that happens when you use autoreleasepool{} block. In the thread brought in the link it wasn't described

Recently I was asked a question

"Explain how an autorelease pool works at the runtime level?"

I know that in ARC retain and release calls are inserted by ObjC runtime library compile time. However I wasn't able to find any appropriate ObjC runtime function that might do that call. So my questions are:

Q1: What happens at runtime when you use autorelease pool?

Q2: What functions are invoked?

Q3: What are the ObjC runtime functions for retain/release?


Solution

  • An autorelease pool is just a data structure that records future releases. Without ARC, when you send -autorelease to an object, a note is made in the autorelease pool. When [pool drain] is eventually called (or equivalently, when the pool is deallocated), it will send one -release to each object for each -autorelease that was requested.

    Without autorelease, MRC would be very inconvenient. Every object returned from a method call would have to be explicitly released. (The called method can't release it, or it would be destroyed before the calling method could access it.)

    ARC's implementation of autorelease is much more complicated. Autorelease introduced various performance impacts. One problem is that an autoreleased object is commonly retained by the caller. This means that in MRC there is very often a "retain/autorelease/retain/defferred-release" dance that is unnecessary and could be replaced by just "retain." The compiler can sometimes detect these, but sometimes this can't be detected until runtime. So there are special ARC methods like objc_retainAutoreleasedReturnValue and objc_autoreleaseReturnValue that inspect the stack at runtime and try to avoid unnecessary autoreleases.

    The details are provided in the ARC documentation for Clang. See the "Runtime support" section.

    As for retain/release, these are implemented by objc_retain and objc_release.