Quartz - CGBitmapContextCreateImage

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

  1. macrumors regular

    Joined:
    Sep 11, 2008
    #1
    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:

    Code:
       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 at iphonedevsdk.com!

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

    Code:
       UIImage  uiImage = [UIImage imageWithCGImage:myRef];
       CGImageRelease (myRef);
       return (uiImage);
    
    Apple's documentation confuses everything with some other problem: CGBitmapContextCreateImage
     
  2. macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    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:

    Code:
    	CGImageRef	ref = CGBitmapContextCreateImage(bitmap);
    	UIImage*	result = [UIImage imageWithCGImage:ref];
    
    	CGContextRelease(bitmap);	// ok if NULL
    	CGImageRelease(ref);
    
    	return result;
    
     
  3. thread starter macrumors regular

    Joined:
    Sep 11, 2008
    #3
    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