
可以看到,每個runloop中都創(chuàng)建一個Autorelease Pool,并在runloop的末尾進行釋放,
所以,一般情況下,每個接受autorelease消息的對象,都會在下個runloop開始前被釋放。也就是說,在一段同步的代碼中執(zhí)行過程中,生成的對象接受autorelease消息后,一般是不會在代碼段執(zhí)行完成前釋放的。
當然也有讓autorelease提前生效的辦法:自己創(chuàng)建Pool并進行釋放
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSArray * array = [[[NSArray alloc] init] autorelease];
[pool drain];
上面的array就會在[pool drain]執(zhí)行時被釋放。
所以對于你遇到的問題,可以在for循環(huán)外嵌套一個Autorelease Pool進行管理,例如
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
for (int i = 0; i < 10000; i++)
{
// ...
}
[pool drain];
但由于你提到了生成的每個實例可能會比較大。只在循環(huán)外嵌套,可能導致在pool釋放前,內(nèi)存里已經(jīng)有10000個實例存在,造成瞬間占用內(nèi)存過大的情況。
因此,如果你的每個實例僅需要在單次循環(huán)過程中用到,那么可以考慮可以在循環(huán)內(nèi)創(chuàng)建pool并釋放
for (int i = 0; i < 10000; i++)
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// ...
[pool drain];
}
如果還有疑問,可以參考下面幾篇資料:
How does the NSAutoreleasePool Work
http://stackoverflow.com/questions/65...
NSAutoreleasePool Class Reference
https://developer.apple.com/library/m...
Autorelease is fast:
http://www.mikeash.com/pyblog/autorel...