End of run loop — autorelease pool recovery

2020-02-17 09:00发布

问题:

As I understand, autoreleased objects are cleaned once an autoreleased pool is released. Now, autorelease pool will be released at the end of the run loop.

My question is, if in my class I am not creating a custom autorelease pool and calling the autorelease method on some objects in that class, at what point will those objects be recovered? Is the "end of the run loop" imply the "end of application"?

回答1:

You have to understand the concept of a run-loop. The run loop in iOS waits for some event to happen and then it acts upon it. That event could be the user touching the screen, receiving a call, etc.

For every such event that iOS handles, a new autorelease pool is created at the beginning and drained when the event processing is complete. Theoretically there could be any number of nested autorelease pools created by Cocoa Touch, but the main one you should know about is the event loop.

Maybe this diagram from the Application Life Cycle will help.

.

In pseudo-code, this boils down to,

int UIApplicationMain(...) {
    while (!shouldQuitApplication) {
        Event *someEvent = // wait for next event;
        NSAutoreleasePool *myPool = [[NSAutoreleasePool alloc] init];
        // handle event
        [myPool release];
    }
}

These are the event types in iOS

UIEventTypeTouches,
UIEventTypeMotion,
UIEventTypeRemoteControl,

So after every touch, motion, or remote control event is processed, the pool will be drained.



回答2:

The "end" of the run loop means the end of each iteration of the run loop, not the end of the application.



回答3:

Not really. Imagine that RunLoop has "circles" :) In the begin of every "circle" RunLoop creates Autorelease pool and drains it before quitting the "circle".