CGColorRef and ARC

A problem I have run into a couple of times recently is the surprising crash that occurs on the device when using CGColorRef's under ARC.

Here is some simple Core Graphics code.

CGContextRef context = UIGraphicsGetCurrentContext();
CGColorRef color = [UIColor whiteColor].CGColor;
CGContextSetFillColorWithColor(context, color);

Looks innocent enough, run it on the device and all of a sudden EXC_BAD_ACCESS. What? First thought is that it must be something wrong with the context because the color is pretty straight forward. However that turns out to be false because it is really the CGColorRef that is causing grief, ARC releases it as soon as the program gets to the next line. This is not a bug and ARC is in fact perfectly correct. Remember that ARC only works on Objective C objects and as there are no references to the UIColor, the memory is released. This leaves our CGColorRef pointing to freed memory. Uh oh.

The fix is as simple as retaining the CGColorRef ourselves as follows:

CGColorRef color = CGColorRetain([UIColor whiteColor].CGColor);
CGContextSetFillColorWithColor(context, color);
CGColorRelease(color);

Problem solved. Of course you could always just condense it into one line and that would also work but sometimes that is a very messy option.

CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);