記憶體管理真的是一個非常重要的議題,處理的好就算記憶體額度有限,也能讓應用程式跑得很順,否則就算給再多的記憶體額度,應用程式依然會崩潰給你看!藉此來研究一下自動釋放池 (Auto Release Pool)。
實驗有無autoreleasepool的差異,方法就是大量跑回圈去增加記憶體的使用量,這裡會從網路下載影像,分別跑100000次。
/**
Theme: Autoreleasepool
IDE: Xcode 5
Language: Objective C
Date: 102/12/29
Author: HappyMan
Blog: https://cg2010studio.wordpress.com/
*/
-(void)withoutReleasePool
{
NSString *url = @"https://cg2010studio.com/wp-content/uploads/2011/12/ban5.png";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
for (int i = 0; i < 100000; i++) {
UIImage *image = [UIImage imageWithData:data];
[self.imageView setImage:image];
}
}
-(void)withReleasePool
{
NSString *url = @"https://cg2010studio.com/wp-content/uploads/2011/12/ban5.png";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
for (int i = 0; i < 100000; i++) {
@autoreleasepool {
UIImage *image = [UIImage imageWithData:data];
[self.imageView setImage:image];
}
}
}
剛開始執行應用程式,記憶體使用量為3.1MB。接著沒有autoreleasepool會累積271MB,而有autoreleasepool會累積191MB,這些得來的數值屢試不爽,還不曉得這樣子的結果是否正常,我期望得到的是~有autoreleasepool所增長的記憶體使用量為0。
找到可參考的虛擬碼,分為有無使用ARC。
//無使用ARC
@autoreleasepool
{
MyObject *obj = [[MyObject alloc] init]; // no autorelease call here
//Since MyObject is never released its a leak even when the pool exits
}
//無使用ARC
@autoreleasepool
{
MyObject *obj = [[[MyObject alloc] init] autorelease];
//Memory is freed once the block ends
}
//使用ARC
@autoreleasepool
{
MyObject *obj = [[MyObject alloc] init];
//No need to do anything once the obj variable is out of scope there are no strong pointers so the memory will free
}
//使用ARC
MyObject *obj //strong pointer from elsewhere in scope
@autoreleasepool
{
obj = [[MyObject alloc] init];
//Not freed still has a strong pointer
}
目前看來理論和實際有一段距離呢!還真希望有高手能來解答我的疑惑~
參考:Using Autorelease Pool Blocks – Apple Developer、iOS autorelease pool blocks、Objective-C: Why is autorelease (@autoreleasepool) still needed with ARC?。

隨意留個言吧:)~