2
votes

I have a question about the autorelease,now I have the code below:

int main(int argc, char *argv[]){
@autoreleasepool {
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}}

the doc says at the end of the @autoreleasepool{} the object marked as autorelease will receive a release message. but the UIApplicationMain never return ,which means the flow will never get to the end of the @autoreleasepool then the object marked as autorelease will never get release until the app die. There has no meaning of autorelease.....

I asked someone who says that the iOS system will generate some threads,(you know,one thread,one runloop).he says that the runloop will create the autorelease pool.so the autorelease object will release at the end of the thead or runloop. But the most situation we use the main thread.so what he says doesn't persuade me.

what's the proper time to use autorelease.It confused me a long time.

I get another point that the autorelease object will get release when one runloop end(the main runloop will exist all the app's life??) so I'm not sure..

any point and related document will be appreciated!!

1
I asked the same question. It is most likely for semantic / demonstration reasons of what is acceptable behavior. The only way out of UIApplicationMain is for the program to exit(), so any memory will be returned to the operating system anyway.borrrden

1 Answers

5
votes

Yes, technically, UIApplicationMain never returns, so it never hits the end of that @autoreleasepool block, so in this case if you removed that @autoreleasepool block it would make no difference (other than maybe things complaining that they have been autoreleased without an autorelease pool). However, it's possible to imagine a main function written in a way that doesn't always call UIApplicationMain (perhaps not in iOS applications, but in general); then it would make a difference.

It is just good practice to always put an @autoreleasepool block around the body of the entry point of every thread, and main is the entry point of the main thread. So for consistency, it makes sense to always put it there.

What the person you talked to is talking about is that inside UIApplicationMain, there is a run loop (an infinite loop that handles events), and inside each iteration there is an autorelease pool (or perhaps every few iterations; it's an implementation detail). This has nothing to do with the autorelease pool in main though.