views:

51

answers:

1

I'm getting an EXC_BAD_ACCESS when releasing newImage on the last line of the following code snippet:

UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

[self setImageToSave:newImage];
[newImage release];

I'm assuming that newImage is released with the call on the preceding line. If so, why is it being released in the setImageToSave method?

+4  A: 

Looks like this line:

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

is creating an autoreleased object. In between that line and before this line:

[newImage release];

..it is getting autoreleased. You're trying to release an autoreleased (and already released) object is why you're getting that error. Remove the release. As for this line:

[self setImageToSave:newImage];

If you need to save newImage for any release you should retain either here or in the setImageToSave method. Remember, since you manually retained it you'll need to match it with a release at some point either within the same method or somewhere else.

Jordan
Moreover, remember that in Cocoa world functions which does not contain world new/copy in methods return autoreleased objects.
Pawel
Thank you so much Jordan. I changed it to `[self setImageToSave:[newImage retain]];` and then I release `[self imageToSave]` in a later method. Does this sound right?
James Skidmore
You really should read the official Apple guide to memory management. Roughly, whatever you retain, you should match with a release. Whatever you init/copy/new you should match with a release. http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
Jordan
@Jordan: More precisely, it is `alloc` that needs to be balanced with a `release`, not `init`.
dreamlax
Yep, my comment should have been alloc/init/copy/new..
Jordan
Gotcha, I'll check out the guide. Thanks again!
James Skidmore