开发者

When is the autorelease pool triggered

开发者 https://www.devze.com 2023-01-11 05:48 出处:网络
i have used autorelease throughout my app and would like to understand the b开发者_Go百科ehavior of the autorelease method. When is the default autorelease pool drained? is it based on a timer (every

i have used autorelease throughout my app and would like to understand the b开发者_Go百科ehavior of the autorelease method. When is the default autorelease pool drained? is it based on a timer (every 30sec?) or have to be called manually? do I need to do anything to release variables that are flagged with autorelease?


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. */
}


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

精彩评论

暂无评论...
验证码 换一张
取 消