AutoreleasePool used in RunLoop

dume0011
1 min readDec 14, 2018

--

AutoreleasePool provide a mechanism whereby you can relinguish ownership of an object, but avoid the possibility of it being deallocated immediately.

RunLoop is an event processing loop that you use to schedule work and coordinate the receipt of incoming events.

RunLoop uses autorelease pool to manage autoreleased objects.

After app is launched, it will registers 2 observers to manage autorelease pool.

One observer is scheduled when kCFRunLoopEntry activity triggered(The entrance of the RunLoop). It will invoke NSPushAutoreleasePool to create autorelease hot page(store autorelease objects).

Another observer is scheduled when kCFRunLoopBeforeWaiting or kCFRunLoopExit activity triggered(before the RunLoop sleep or exit of the RunLoop).

When kCFRunLoopBeforeWaiting, will invoke NSPopAutoreleasePool to pop a hot page, and then NSPushAutoreleasePool again.

when kCFRunLoopExit, will invoke NSPopAutoreleasePool only.

Simple RunLoop Flowchart

NSPushAutoreleasePool first pushes a sentinel object into autorelease pool, the observer will store the sentinel object in an array. Autoreleased objects then pushed after the sentinel.

NSPopAutoreleasePool will fetch sentinel object from the array in the observer, it iterates to release autoreleased objects and drop them in the autorelease pool, until found the sentinel object.

So RunLoop automatically manages the autorelease pool, autoreleased objects will not be leaked.

--

--

No responses yet