UIKit and Quartz Colors
Many Core Foundation classes have UIKit equivalents and vice versa. Often these are toll free bridged, which means the Core Foundation-style data types can be used interchangeably with UIKit version. You use ARC bridging calls (__bridge) to move between the Core Foundation-style version and the UIKit version. Toll-free bridging is notably absent from many Quartz/UIKit relationships, including colors.
Most drawing routines and classes in UIKit represent Objective-C wrappers around Quartz functions and Core Graphics objects. UIColor holds a CGColor inside it. UIBezierPath instances include CGPath internals. UIImage wraps CGImage or CIImage. These wrappers are not, however, equivalent objects. Although you can easily access the backing Quartz elements, they can’t be bridged.
In UIKit, the UIColor class represents color and opacity values. You create these by using a variety of entry points, but the most common approaches involve supplying either RGB values (colorWithRed:green:blue:alpha:) or HSV values (colorWithHue:saturation:brightness:alpha:) to the class.
When working with Core Graphics, you’ll find yourself moving back and forth between UIKit and Quartz. To assist with this, every UIColor offers a CGColor property. This property offers a Quartz CGColorRef corresponding to the instance’s color and alpha values.
You use this property to provide compliant parameters to Quartz. For example, consider the following line of code:
CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor);
This function call consists of a Quartz routine that sets a context’s fill color. The second parameter starts with the standard green preset from UIColor. Its CGColor property provides a type that represents a Quartz 2D drawing color, which can safely be used with the Core Graphics function.
Take special care when separating or referencing a Quartz color from its UIKit wrapper. You may need to manually retain that color so its lifetime extends beyond the scope of its parent. Many devs have gotten caught by ARC’s memory management, encountering freed memory errors when passing a CGColorRef variable that no longer points to a valid instance. Mark Dalrymple of the Big Nerd Ranch discusses this issue in http://blog.bignerdranch.com/296-arc-gotcha-unexpectedly-short-lifetimes.
To move back to UIKit from Quartz, use the class constructor method. This builds a UIKit instance from the Core Graphics object reference:
UIColor *color = [UIColor colorWithCGColor:myCGColorRef];