views:

1318

answers:

5

If I use [UIImage imageWithCGImage:], passing in a CGImageRef, do I then release the CGImageRef or does UIImage take care of this itself when it is deallocated?

The documentation isn't entirely clear. It says "This method does not cache the image object."

Originally I called CGImageRelease on the CGImageRef after passing it to imageWithCGImage:, but that caused a malloc_error_break warning in the Simulator claiming a double-free was occurring.

+1  A: 

I agree with you -- the documentation is muddled at best for this API. Based on your experiences, then, I would conclude that you are responsible for the lifetime of both objects - the UIImage and the CGImageRef. On top of that you have to make sure the lifetime of the CGImageRef is at least as long as the UIImage (for obvious reasons).

fbrereto
Not definitive, but I'll take it.
Adam Ernst
A: 

Are you using Xcode 3.1 on Snow Leopard? I am experiencing the same issue:

CGContextRef ctx = ...;
CGImageRef cgImage = CGBitmapContextCreateImage(ctx);
UIImage * newImage = [[UIImage imageWithCGImage:cgImage] retain];

CGImageRelease(cgImage); // this should be OK, but it now crashes in Simulator on SL

I'm guessing that upgrading to Xcode 3.2 will fix the issue.

Jason
+2  A: 

I have the same problem in XCode 3.2.1 on Snow Leopard. I have pretty much the same code as Jason.

I have looked at the iPhone sample code which uses imageWithCGImage and they always release the CGImageRef using CGImageRelease after a call to imageWithCGImage.

So, is this a bug in the simulator? I always get the malloc_error_break warning on the console when I use CGImageRelease.

Lextar
This should be a comment on Jason's answer, or a new question, as SO isn't a forum.
outis
I can not comment other people's posts because I do not have enough "reputation". Besides, this isn't a new question. I simply suggested that the problem might only happen in the simulator but not on the device.
Lextar
A: 

According to the fundamental rule of Cocoa memory management, an owning object should release the owned object when it no longer needs it. Other objects are responsible for taking and releasing ownership on their own. If a UIImage needs an object to persist but doesn't retain or copy it, it's a bug in UIImage's implementation and should be reported as such.

outis
A: 

<> Not my opinion. I had the same problem. According to documentation

UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];

imho keeps all references correct. If you are using a CGDataProvider please have a look at CGDataProviderReleaseDataCallback and set a breakpoint in your callback. You can see that is is correctly called after you [release] your image and you can free() your image data buffer there.

christian