4

我有一个使用 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;
}

在我开始使用 Instruments 以确保没有任何内存泄漏之前,我认为一切都很好,但我发现像这样将 UIButton 添加为单元格的子视图会导致 UIKit 中的泄漏。

具体来说,我得到每个单元格行的内存泄漏(每次将按钮添加为子视图),泄漏的对象是“CALayer”,负责的框架是“-[UIView _createLayerWithFrame:]”。

我在这里做错了吗?

4

3 回答 3

5

代码 [UIButton buttonWithType] 方法已经包含一个 initWithFrame 方法。您只需要使用 CGRectMake,然后设置按钮的框架。

rectangle = CGRectMake(2.0f,2.0f,40.0f,40.0f);
checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
checkButton.frame = rectangle;
于 2010-02-22T19:17:32.333 回答
0

您是否在物理设备模拟器上对此进行了测试?

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

否则,您的代码对我来说是正确的。

于 2010-02-22T19:16:27.763 回答
0

checkButton 是您班级的@property(retain) 吗?

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

此外,您应该在 addSubview 之后放置一个 [checkButton release],因为 addSubview 代码是它自己的保留/释放

于 2010-02-22T19:16:30.557 回答