【问题标题】:help with memory issues on adding a UIImageView to a cell帮助解决将 UIImageView 添加到单元格的内存问题
【发布时间】:2011-05-16 23:50:28
【问题描述】:

我正在向 UITableView cellForRowAtIndexPath 中的第一个单元格添加图像,如下所示:

if (row == 0) {
        UIImage *image = [UIImage imageNamed:@"numberOneIcon.png"];
        //create a framework for the ui image view
        CGRect frame = CGRectMake(10, 37, image.size.width, image.size.height);
        //initialize the ui image view
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        imageView.image = image;

        [cell.contentView addSubview:imageView];
        [image release];
        //[imageView release];
}

如果我取消注释 [imageView release];当您“关闭”应用程序(按主页 bttn)然后返回应用程序并返回到其中包含 UITableView 的视图时,它将崩溃。

如果我留下评论,它不会崩溃,但我不是在这里泄漏内存吗?如果是这样,还有其他方法可以做到这一点,以免泄漏。

非常感谢

【问题讨论】:

    标签: iphone uitableview uiimageview memory-management


    【解决方案1】:

    你应该发布 imageView 而不是 image。将该代码更改为以下内容:

    [cell.contentView addSubview:imageView];
            //[image release];
            [imageView release];
    

    您不拥有图像,因为您没有使用 alloc、new 创建它,也没有保留它,因此您不应该释放它。但是,您确实分配了 imageView 的实例,所以这就是您发布的内容。我强烈推荐阅读this

    【讨论】:

    • 太好了,太明显了,谢谢你的快速回答队友,我确实需要通读MM指南
    【解决方案2】:

    你也可以使用:

        UIImageView *imageView = [[[UIImageView alloc] initWithFrame:frame] autorelease];
    

    为了您的方便,

    【讨论】:

    • 谢谢伙计。说最好的做法是在上面的 alloc 之后释放而不是 autoRelease 是否正确?我知道这两种方法都有效,但哪种方法效果最好?
    • 前一个(从确认的角度来看),它确保你已经做到了......当你想要的时候......
    猜你喜欢
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多