2012-02-07 116 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应该被释放,另外,如果你的方法创建一个实例,并保留它,它的名字已经重新开始与“新”,“复制”或“黄金”

相关问题