閱讀862 返回首頁    go 阿裏雲 go 技術社區[雲棲]


iOS開發那些事-性能優化–autorelease的使用問題

在MRR中釋放對象通過release或autorelease消息實現,release消息會立刻使引用計數-1釋放,發送autorelease消息會使對象放入內存釋放池中延遲釋放,對象的引用計數並不真正變化,而是向內存釋放池中添加一條記錄,直到當池被銷毀前會通知池中的所有對象全部發送release消息真正將引用計數減少。

由於會使對象延遲釋放,除非必須,否則不要使用autorelease釋放對象,在iOS程序中默認內存釋放池的釋放是在程序結束,應用程序入口main.m文件代碼如下:

int main(int argc, char *argv[])

{

@autoreleasepool {

return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));

}

}


代碼被包裹在@autoreleasepool {… }之間,這是池的作用範圍,默認是整個應用。如果產生大量對象采用autorelease釋放也會導致內存泄漏。那麼什麼時候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];

}

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;

}


其中的cell對象不能馬上release,我們需要使用它設置表視圖畫麵。autorelease一般應用於為其它調用者提供對象的方法中,對象在該方法不能馬上release,而需要延遲釋放。

此外,還有一種情況下使用了autorelease,即前文提到的“類級構造方法”:

NSString *message = [NSString stringWithFormat:@"您選擇了%@隊。", rowValue];

該對象的所有權雖然不是當前調用者,但它是由iOS係統通過發送autorelease消息放入到池中的,當然這一切對於開發者都是不可見的,我們也要注意減少使用這樣的語句。


最後更新:2017-04-04 07:03:44

  上一篇:go zend studio代碼自動提示問題,有的提示正常有的提示不正常,解決方法
  下一篇:go UbuntuEclipse顏色提示修改(WinXP窗口背景顏色修改)+快捷方式啟動