When is the autorelease pool triggered

后端 未结 2 1191
被撕碎了的回忆
被撕碎了的回忆 2021-01-13 14:11

i have used autorelease throughout my app and would like to understand the behavior of the autorelease method. When is the default autorelease pool drained? is it based on a

相关标签:
2条回答
  • 2021-01-13 14:38

    There are (I'd say) 3 main instances when they are created and release:

    1.Beginning and very end of your application life-cycle, written in main.m

    int main(int argc, char *argv[]) { 
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
        int retVal = UIApplicationMain(argc, argv, nil, nil); 
        [pool release]; 
        return retVal; 
    }
    

    2.Beginning and very end of each event (Done in the AppKit)

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
    - (void)loadView 
    /* etc etc initialization stuff... */
    [pool release];
    

    3.Whenever you want (you can create your own pool and release it. [from apples memory management document])

    – (id)findMatchingObject:anObject { 
        id match = nil; 
        while (match == nil) { 
            NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init]; 
            /* Do a search that creates a lot of temporary objects. */ 
            match = [self expensiveSearchForObject:anObject]; 
            if (match != nil) { 
                [match retain]; /* Keep match around. */ 
            } 
            [subPool release]; 
        } 
        return [match autorelease];   /* Let match go and return it. */
    }
    
    0 讨论(0)
  • 2021-01-13 14:51

    It is drained whenever the current run-loop finishes. That is when your method and the method calling your method and the method calling that method and so on is all done.

    From the documentation:

    The Application Kit creates an autorelease pool on the main thread at the beginning of every cycle of the event loop, and drains it at the end, thereby releasing any autoreleased objects generated while processing an event

    0 讨论(0)
提交回复
热议问题