PDA

View Full Version : Quartz - CGBitmapContextCreateImage




idelovski
Apr 30, 2009, 10:19 AM
In the iPhone book by Erica Sadun there are several places where she uses the function createImage() to crate an image on the fly with some text or graphics.

Those functions usually end like this:

CGImageRef myRef = CGBitmapContextCreateImage (context);
free(CGBitmapContextGetData(context));
CGContextRelease(context);

return [UIImage imageWithCGImage:myRef];


And on the web I found several similar functions, this one for example (http://www.iphonedevsdk.com/forum/iphone-sdk-development/13540-drawing-uiimage-memory-issues.html) at iphonedevsdk.com!

So, is there a memory leak? Do they need to call CGImageRelease() before returning an UIImage instance?


UIImage uiImage = [UIImage imageWithCGImage:myRef];
CGImageRelease (myRef);
return (uiImage);


Apple's documentation confuses everything with some other problem: CGBitmapContextCreateImage (http://developer.apple.com/documentation/graphicsimaging/reference/CGBitmapContext/Reference/reference.html#//apple_ref/c/func/CGBitmapContextCreateImage)



PhoneyDeveloper
Apr 30, 2009, 04:21 PM
Yes, the code you show has a memory leak. CGBitmapContextCreateImage follows the Create Rule and the created CGImage must be released.

Code usually looks something like this:

CGImageRef ref = CGBitmapContextCreateImage(bitmap);
UIImage* result = [UIImage imageWithCGImage:ref];

CGContextRelease(bitmap); // ok if NULL
CGImageRelease(ref);

return result;

idelovski
Apr 30, 2009, 07:09 PM
Thanks for your reply.

At first I was sure there was a leak, but wherever I looked there was that same (wrong) pattern and then I wasn't so sure any more.