您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iPhone 開發工具篇:用 Xcode Profile 與 Analyze 做效能優化

編輯:iOS 開發綜合

內存洩漏問題的由來

內存洩漏(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 的兩大幫手

Xcode 提供了兩種工具來查找洩漏點:

  • Analyze:靜態分析工具,可透過菜單 Product → Analyze 啟動,對靜態分析後的代碼給出提示畫面。
  • Profile:動態分析工具,也就是「Instruments」。它與 Xcode 集成在一起,可透過菜單 Product → Profile 啟動。Instruments 內建眾多 Trace Template(跟蹤模板),能動態分析和跟蹤記憶體、CPU 以及檔案系統。

借助這兩件工具,你就能在 MRR 環境下有效揪出洩漏點,逐一消除內存洩漏的隱患。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved