Why is this leaking memory? UIImage `cellForRowAtIndexPath:`
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 UII开发者_C百科mage allocated here in the code leaks
.
Can you help me figure it out? Thanks :)
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;
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;
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];
精彩评论