Having trouble with releases in core graphics

I've just started with releasing in core graphics, so I might need a little help.

I have code which looks like this:

UIImage *buttonImage() {

UIGraphicsBeginImageContextWithOptions(bounds.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();

    CGMutablePathRef outerPath;
    CGMutablePathRef midPath;
    CGMutablePathRef innerPath;
    CGMutablePathRef highlightPath;

//Some button stuff

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();



    return image;


That release line, I've put in. I'm getting an error with it though:

context_reclaim: invalid context
context_finalize: invalid context

Any thoughts as to where i should put the release in this instance?


You only need to do CGContextRelease(context) if you have previously done a CFRetain(context) or a CGContextRetain(context), or if you created the context yourself. In your example, you are calling UIGraphicsBeginImageContextWithOptions(), which is handling the creation of the context for you, thus, calling CGContextRelease() yourself is over-releasing it.

You do need to balance the CGColorSpaceCreateDeviceRGB() with either a:


or a :

if (baseSpace) CFRelease(baseSpace)

You don't own the context when using UIGraphicsGetCurrentContext. Therefore you should not be releasing it. If you were to use CGContextRetain() then you would release. More information of this is available here:

Memory Management Guide for Core Foundation

I highly suggest reading the Memory Management programming guide to get an understanding of how it works.

Need Your Help

Automatically update UITableView when Array changes

iphone ios arrays uitableview nsmutablearray

I have a View Controller containing a UITableView that used an NSMutableArray to determine its content via the usual UITableViewDelegate and UITableViewDataSource methods.

Is there a better way than a sequence of if's to handle events?

java mapping abstraction

I recently ran across several objects implemented to handle events with a hard coded mapping using this pattern: