I have the following code:
...
UIImage *image;
CGImageRef imageRef;
image = [[[UIImage alloc] initWithContentsOfFile: filePath] retain];
while (some_condition)
{
NSAutoreleasePool *pool = [[NSAutoReleasePool alloc] init];
imageCGDATA = CGDataProviderCreateWithCFData(cfdata);
imageRef = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, bitmapInfo, imageCGDATA, NULL, NO, intent);
CGDataProviderRelease(imageCGDATA);
[image release];
image = [[[UIImage alloc] initWithCGImage: imageRef]] retain]; // LEAK HERE
CGImageRelease(imageRef);
[pool release];
}
...
When I run the code and look at Allocations I see total “Live Bytes” grow as each iteration of the loop completes, and the number of “CGImage” and “UIImage” Living allocations grow to very large numbers (obviously depends upon the number of iterations of the loop).
If I comment the line of code annotated with “LEAK HERE” (and the release immediately preceding that line of code) and re-run the app, then “Live Bytes”, number of “CGImage” and “UIImage” Living allocations remain static over many iterations of the loop.
Why does that code leak? What am I missing?
Thanks.
You don’t need the retain in:
image = [[[UIImage alloc] initWithCGImage: imageRef]] retain];You’re calling
alloc, so the returned object already has aretainCountof 1. Retaining it again increments theretainCountto 2, but you only release it once before you reassign the pointer on the next loop iteration. So an instance leaks because theretainCountwas left at 1.So long story short, this should fix it:
image = [[UIImage alloc] initWithCGImage: imageRef]];