【问题标题】:detected potential leak by analyze通过分析检测到潜在泄漏
【发布时间】:2012-04-25 02:09:34
【问题描述】:

以下是我的代码:

    UIImage *takePhotoImg = [UIImage imageNamed:@"add_pic.png"];
    self.takePhoto = [[UIButton alloc] initWithFrame:CGRectMake(120, 100, takePhotoImg.size.width, takePhotoImg.size.height)];
    [_takePhoto setImage:takePhotoImg forState:UIControlStateNormal];
    [_takePhoto addTarget:self action:@selector(takePhotoBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_takePhoto];

当我使用分析时,它显示以下行:

[_takePhoto setImage:takePhotoImg forState:UIControlStateNormal];

已分配对象的潜在泄漏。 我需要添加版本,还是直接忽略?
提前谢谢你

更新: 我确实在我的 dealloc 中释放了按钮 _takePhoto:

-(void)dealloc
{
    [_takePhoto release];
    [super dealloc];
}

我的财产:

@property(nonatomic,retain)UIButton *takePhoto;

【问题讨论】:

    标签: ios memory-leaks


    【解决方案1】:

    如果您不使用 ARC,那么是的,您需要释放它。当您将其添加到self.view 的子视图时,self.view 将保留它,因此按钮不会消失。

    如果您不需要访问按钮并且不需要保留引用,则可以在addSubview: 调用后立即释放它。

    但是,takePhoto 似乎是您班级的一个属性。如果是这种情况并且您想保留对按钮的引用以供以后使用,只需将[_takePhoto release] 调用添加到您的类dealloc 方法。这应该会抑制代码分析警告。

    【讨论】:

    • 在这种情况下,请尝试在示例的第 2 行使用 _takePhoto 而不是 self.takePhoto。我相信使用self.takePhoto 将有效地“双重保留”(因为该属性具有retain 特征),这不是您想要的。
    【解决方案2】:

    更改代码:

        self.takePhoto = [[UIButton alloc] initWithFrame:CGRectMake(120, 100,      takePhotoImg.size.width, takePhotoImg.size.height)];
    

        self.takePhoto = [[[UIButton alloc] initWithFrame:CGRectMake(120, 100, takePhotoImg.size.width, takePhotoImg.size.height)] autorelease];
    

    delloc 方法中的[_takePhoto release] 用于setter 方法中的retain。每次调用 self.takePhoto = aNewTakePhote,aNewTakePhote 都会被保留一次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多