1. NSAutoreleasePool實際上是個對象引用計數自動處理器。NSAutoreleasePool可以同時有多個,它的組織是個棧,總是存在一個棧頂pool,也就是當前pool,每創建一個pool,就往棧裏壓一個,改變當前pool爲新建的pool,然後,每次給pool發送drain消息,就彈出棧頂的pool,改當前pool爲棧裏的下一個 pool。
2. 在程序的入口main函數就調用NSAutoreleasePool,這樣保證程序中不調用NSAutoreleasePool,但在退出時自動釋放。新開線程最好實現NSAutoreleasePool
3. NSAutoreleasePool的管理範圍是在NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];與[pool release];之間的對象
4. NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
當執行[pool autorelease]的時候,系統回進行一次內存釋放,把autorelease的對象釋放掉,如果沒有NSAutoreleasePool , 那這些內存不會釋放
注意,對象並不是自動被加入到當前pool中,而是需要對對象發送autorelease消息,這樣,對象就被加到當前pool的管理裏了。噹噹前pool接受到drain消息時,它就簡單的對它所管理的所有對象發送release消息。
例如
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString* nsstring;
char* cstring = "Hello CString";
nsstring = [NSString stringWithUTF8String:cstring];
[pool release];
5. alloc的對象必須顯示釋放
例如:
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString* string = [[NSString alloc] init];
[string stringByAppendingString:@"Hello World!"];
[pool release];
[nsstring release];