When is the autorelease pool triggered

后端 未结 2 1210
被撕碎了的回忆
被撕碎了的回忆 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. */
    }
    

提交回复
热议问题