Iphone 为什么在将按钮添加为子视图时会出现内存泄漏?

Iphone 为什么在将按钮添加为子视图时会出现内存泄漏?,iphone,uikit,uitableview,uibutton,instruments,Iphone,Uikit,Uitableview,Uibutton,Instruments,我有一个使用tableview的应用程序,还有一个UIButton,我将其作为子视图添加到每个自定义单元格中,如下所示: UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellI

我有一个使用tableview的应用程序,还有一个UIButton,我将其作为子视图添加到每个自定义单元格中,如下所示:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

    checkButton = [[UIButton buttonWithType:UIButtonTypeCustom] initWithFrame:CGRectMake(2.0, 2.0, 40.0, 40.0)];
    [cell.contentView addSubview:checkButton];

    // lot's of other code

    return cell;
}
我一直认为一切都很好,直到我开始使用仪器来确保我没有任何内存泄漏,但我发现,添加UIButton作为单元格的子视图会导致UIKit中出现泄漏

具体来说,我为每个单元格行(每次按钮作为子视图添加时)获取内存泄漏,泄漏的对象是“CALayer”,负责的帧是“-[UIView\U createLayerWithFrame:”

我做错什么了吗?

您在物理设备或模拟器上测试过吗

已知模拟器与实际设备代码相比存在一些内存管理变化您应该始终在真实设备上运行内存泄漏测试。

否则,您的代码在我看来是正确的。

checkButton是类的@property(retain)吗

因为在这种情况下,您应该在使用后将属性设置为null。。。但是你不能,因为细胞的生命周期不在你的控制之下;使用局部变量会更好


此外,您应该在addSubview之后放置一个[checkButton release],就像addSubview代码一样,它自己的保留/释放[p>代码[UIButton buttonWithType]方法已经包含一个initWithFrame方法。您只需使用CGRectMake,然后设置按钮的框架

rectangle = CGRectMake(2.0f,2.0f,40.0f,40.0f);
checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
checkButton.frame = rectangle;

不,您不应该调用
[checkButton release]
,因为它从未被分配、新建或复制。但是,如果它是保留的属性,您可以很好地将其置零。按钮是通过类方法创建的,因此会自动删除。对不起,我错过了自动删除功能。Jawbox没有使用属性设置程序。所以没有理由释放。这就解决了它!谢谢你的帮助。(还有,伙计,你们的反应很快,呵呵)一张便条,加上“UIButton*checkButton=”会导致我的应用程序崩溃。。。但让它像我拥有的一样(“checkButton=”)似乎可以正常工作。抱歉,看起来您必须在标题中声明它。如果允许,我会编辑我的评论!