2012-02-07 66 views
1

我剛開了這些,而我分析我的代碼:方法返回一個+1 Objective-C的對象保留計數

Method returns an Objective-C object with a +1 retain count 

Object leaked: object allocated and stored into 'headerLabel' is not referenced later in this execution path and has a retain count of +1 
這種方法

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
    { 
     // create the parent view that will hold header Label 
     UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(15.0, 0.0, 300.0, 44.0)]; 

     // create the button object 
     UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero]; 
     headerLabel.backgroundColor = [UIColor clearColor]; 
     headerLabel.opaque = NO; 
     headerLabel.textColor = [UIColor whiteColor]; 
     headerLabel.highlightedTextColor = [UIColor whiteColor]; 
     headerLabel.font = [UIFont boldSystemFontOfSize:15]; 
     headerLabel.frame = CGRectMake(10.0, 0.0, 300.0, 44.0); 

     if (section == 0) 
      headerLabel.text = NSLocalizedString(@"A", @"A"); 
     else if (section == 1) 
      headerLabel.text =NSLocalizedString(@"B", @"B"); 
     else if (section == 2) 
      headerLabel.text = NSLocalizedString(@"C", @"C"); 

     if(searching) 
      headerLabel.text = NSLocalizedString(@"SEARCH", @"Search Results"); 

     [customView addSubview:headerLabel]; 

     return customView; 
    } 

現在,擴大我試圖理解上的箭頭,我想是customView不是DEA llocated。這樣對嗎?

我該如何解決這個問題?我是新手,幫助我理解!

回答

5

要麼添加

[headerLabel release]; 

[customView addSubview:headerLabel]; 

或初始化像這樣

UILabel * headerLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease]; 
當然

因爲你不使用ARC

+0

,如果你不使用ARC,添加autorelease到customView初始化或返回[contentView autorelease];由於viewForHeader方法意味着視圖應該被自動釋放。 – Eugene 2012-02-07 18:22:08

+0

謝謝,我嘗試了你的建議,現在它的工作原理!沒有更多的泄漏 – Phillip 2012-02-07 18:30:16

1
[customView addSubview:headerLabel]; 

此行後您應該發佈headerLabel變量。

瞭解對象所有權的概念很重要。在 目標C中,對象所有者是某人(或一段代碼),它明確地說:「對,我需要這個對象,不要刪除它」。此 可能是創建對象 的人員(或代碼)。或者它可以是另一個人(或代碼),它接收到該對象並需要它。 因此,一個對象可以有多個所有者。對象擁有者 的擁有者數量也是引用計數。

看看這個Memory Management with Objective C/Cocoa/iPhone。 在你的代碼中,你創建了headerLabel,所以你是該對象的所有者;你必須釋放該對象。

0

headerLabel應該被釋放,另外,如果你的方法創建一個實例,並保留它,它的名字已經重新開始與「新」,「複製」或「黃金」

相關問題