記憶體洩漏(Memory Leaks)指的是一個物件或變數在用完之後沒有被釋放,於是本該歸還的記憶體一直被它佔著,直到應用結束。洩漏的物件累積得夠多,記憶體就會耗盡,App 被系統終止,嚴重的還會拖垮其他應用。
在 C、C++ 以及 Objective-C 的 MRR(手動引用計數)環境下,這是相當常見的問題。
Objective-C 靠 release 與 autorelease 兩則訊息來管理物件生命週期,兩者都會讓引用計數減 1,差別在時機:
- (void)viewDidLoad
{
[super viewDidLoad];
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"team" ofType:@"plist"];
// 讀取屬性列表中的全部資料
self.listTeams = [[[NSArray alloc] initWithContentsOfFile:plistPath] autorelease];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *rowDict = [self.listTeams objectAtIndex:[indexPath row]];
cell.textLabel.text = [rowDict objectForKey:@"name"];
NSString *imagePath = [rowDict objectForKey:@"image"];
imagePath = [imagePath stringByAppendingString:@".png"];
cell.imageView.image = [UIImage imageNamed:imagePath];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *rowDict = [self.listTeams objectAtIndex:[indexPath row]];
NSString *rowValue = [rowDict objectForKey:@"name"];
NSString *message = [[[NSString alloc] initWithFormat:@"您選選擇了 %@ 隊。", rowValue] autorelease];
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"請選擇球隊"
message:message
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil] autorelease];
[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
這三個方法在 ARC 下沒問題,但在 MRR 下都有洩漏的可能——凡是用 alloc / init / copy 取得所有權的物件,記得都要有對應的 release 或 autorelease。
理論上洩漏源自物件未釋放,但實務上並非所有未釋放的物件都會造成可觀的問題,這與硬體環境、作業系統的記憶體回收策略有關。換句話說,光靠肉眼與 code review 很難判斷哪些才是真正需要處理的「洩漏點」,我們需要工具。
從選單 Product → Analyze 啟動。它在編譯期掃描程式碼,找出邏輯上明顯的記憶體問題:alloc 後沒有 release、有 release 卻沒 alloc、把物件放進容器後又釋放導致過早銷毀等等。
它會直接在程式碼行號旁標出警告,並用箭頭串起「物件在哪裡產生、在哪裡被漏掉」的路徑。這是最低成本的日常檢查,建議每次存檔後順手跑一次。
從 Product → Profile 啟動,Xcode 會開啟整合的 Instruments。它提供大量 Trace Template,可以在執行期追蹤記憶體、CPU、檔案系統等各種指標。
找洩漏最常用的兩個模板: