Quartz - CGBitmapContextCreateImage

Discussion in 'iOS Programming' started by idelovski, Apr 30, 2009.

  1. idelovski macrumors regular

    Sep 11, 2008
    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);
       return [UIImage imageWithCGImage:myRef];
    And on the web I found several similar functions, this one for example 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
  2. PhoneyDeveloper macrumors 68030


    Sep 2, 2008
    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
    	return result;
  3. idelovski thread starter macrumors regular

    Sep 11, 2008
    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.

Share This Page