为什么这会泄漏内存? UIImage cellForRowAtIndexPath: [英] Why is this leaking memory? UIImage `cellForRowAtIndexPath:`

查看:92
本文介绍了为什么这会泄漏内存? UIImage cellForRowAtIndexPath:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Instruments的泄漏告诉我该UIImage正在泄漏:

Instruments' Leaks tells me that this UIImage is leaking:

UIImage *image = [[UIImage alloc] initWithContentsOfFile:[imagesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@.png", [postsArrayID objectAtIndex:indexPath.row]]]];

// If image contains anything, set cellImage to image. If image is empty, try one more time or use noImage.png, set in IB
if (image != nil){
    // If image != nil, set cellImage to that image
    cell.cellImage.image = image;
}
image = nil;
[image release];

(类单元格(自定义表格视图单元格)也会在dealloc方法中释放cellImage.)

(class cell (custom table view cell) also releases cellImage in dealloc method).

我不知道它为什么泄漏的线索,但确实如此. 图像在cellForRowAtIndexPath:方法中多次加载.前三个单元格的图像不会泄漏(130px高,所有空间可用).

I haven't got a clue of why it's leaking, but it certainly is. The images gets loaded multiple times in a cellForRowAtIndexPath:-method. The first three cells' image does not leak (130px high, all the space avaliable).

泄漏除了提供UIImage allocated here in the code leaks之外没有其他信息.

Leaks gives me no other info than that a UIImage allocated here in the code leaks.

您能帮我弄清楚吗?谢谢:)

Can you help me figure it out? Thanks :)

推荐答案

如果image是@property,则您拥有的代码将是正确的.您可以通过执行self.property = nil来释放@property,这是因为setter的工作方式.设置器释放旧对象,并将ivar设置为该值.为了解决此问题,您需要先放置[image release].这里发生的事情是将image设置为nil,然后实际上是在做[nil release].旧的图像只是漂浮在某个地方.因此,要解决此问题,请执行以下操作:

The code you have there would be correct if image was a @property. You can release a @property by doing self.property = nil because of the way the setter works. The setter releases the old object and sets the ivar to the value. In order to fix this you would need to put [image release] first. What is happening here is that you set image to nil and then you are essentially doing [nil release]. The old image is just floating around somewhere. So to fix this do the following:

[image release];
image = nil;

这篇关于为什么这会泄漏内存? UIImage cellForRowAtIndexPath:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆