Getting CGColor from UIColor in iOS

CGColor Memory Issues

I have an IOS app that I have been writing that requires color information to be stored as printable text.  To do this I use CGColorGetComponents, which returns a CGFloat array of color components.  I had been having an issue with the text color turning transparent after using these functions and last night I found the problem.

The problem was that when the color is black or white (if color space is gray scale for example), CGColorGetComponents only returns an array with 2 CGFloats contained within.  I was detecting this correctly (with CGColorGetNumberOfComponents) but I was doing was:

components[2] = components[1] = components[0];

Which, since the components array only had two elements in it (from CGColorGetComponents), overwrote memory of another variable,  leading to bizarre results later on in the code, such as all the text disappearing.

The corrected code is shown below.  I hope this helps somebody out.

 CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0;
 
 
 CGFloat *components = (CGFloat *) CGColorGetComponents(toTextColor.CGColor);
 if(CGColorGetNumberOfComponents(toTextColor.CGColor) == 2)
 {
 //assuming it is grayscale - copy the first value
 
 red = components[0];
 blue =components[0];
 green =components[0];
 alpha = components[1];
 }
 else
 {
 
 red = components[0];
 green = components[1];
 blue = components[2];
 alpha = components[3];
 }
 

 NSString *TcolorAsString = [NSString stringWithFormat:@"%f,%f,%f,%f", red, green, blue, alpha];