Why is this leaking memory? UIImage `cellForRowAtIndexPath:`

陌路散爱 提交于 2019-12-23 05:04:02

问题


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 :)


回答1:


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;



回答2:


You are setting it to nil before calling release. So you are releasing nil instead of image.

Change from:

image = nil;
[image release];

to:

[image release];
image = nil;



回答3:


Little bit code modification

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

 if (image){
    cell.cellImage.image = image;
    [image release];


来源:https://stackoverflow.com/questions/2961312/why-is-this-leaking-memory-uiimage-cellforrowatindexpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!