为什么会泄漏内存? UIImage `cellForRowAtIndexPath:`
Instruments 的 Leaks 告诉我这个 UIImage 正在泄漏:(
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];
类 cell(自定义表视图单元)也在 dealloc 方法中释放了 cellImage)。
我不知道为什么会泄漏,但确实如此。 图像在 cellForRowAtIndexPath: 方法中多次加载。前三个单元格的图像不会泄漏(130 像素高,所有可用空间)。
Leaks 除了在代码泄漏中分配的 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];
(class cell (custom table view cell) also releases cellImage in dealloc method).
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).
Leaks gives me no other info than that a UIImage allocated here in the code leaks
.
Can you help me figure it out? Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果图像是
@property
,那么您的代码将是正确的。由于 setter 的工作方式,您可以通过执行 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:您在调用
release
之前将其设置为nil
。因此,您将释放nil
而不是image
。从: 更改
为:
You are setting it to
nil
before callingrelease
. So you are releasingnil
instead ofimage
.Change from:
to:
稍微修改一下代码
Little bit code modification