內存洩漏(Memory Leaks)是指一個物件或變量在使用完成後沒有被釋放,於是一直佔著那塊記憶體,直到應用停止。如果這類物件過多,記憶體就會耗盡,其他應用也無法運行。這個問題在 C++、C 以及 Objective-C 的 MRR(手動引用計數)環境中比較普遍。
在 Objective-C 中,釋放物件記憶體是發送 release 和 autorelease 訊息,它們都能讓引用計數減 1:當引用計數為 0 時,release 會讓物件立刻釋放,而 autorelease 則把物件放進記憶體釋放池延遲釋放。
- (void)viewDidLoad {
[super viewDidLoad];
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource:@"team" ofType:@"plist"];
self.listTeams = [[NSArray alloc] initWithContentsOfFile:plistPath];
}
- (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];
}
NSUInteger row = [indexPath row];
NSDictionary *rowDict = [self.listTeams objectAtIndex: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 {
NSUInteger row = [indexPath row];
NSDictionary *rowDict = [self.listTeams objectAtIndex:row];
NSString *rowValue = [rowDict objectForKey:@"name"];
NSString *message = [[NSString alloc] initWithFormat:@"您選擇了%@隊。", rowValue];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"請選擇球隊"
message:message delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
看看這三個方法有什麼問題?如果代碼基於 ARC,是沒有問題的;遺憾的是它基於 MRR,那麼上面的代碼都存在內存洩漏的可能。
理論上講,內存洩漏是物件或變量沒有釋放引起的;但實踐證明,並非所有未釋放的物件都會導致洩漏,這與硬件環境和作業系統環境有關。因此我們需要檢測工具來幫助定位這些「洩漏點」。
Xcode 提供了兩種工具來查找洩漏點:
借助這兩件工具,你就能在 MRR 環境下有效揪出洩漏點,逐一消除內存洩漏的隱患。