unmircea unmircea - 3 months ago 11
Objective-C Question

UIColor conversion to string fails, why?

I have two pieces of code, first fails the second works... can't see why.

UIColor _color = [UIColor blackColor];


NSString *something1 = [[_color CIColor] stringRepresentation]; //Fails
NSString *something = [[CIColor colorWithCGColor:[_color CGColor]] stringRepresentation]; //works

Can anyone explain?

Answer

From Apple's UIColor documentation here, this is because the CIColor property:

throws an exception if the color object was not initialized with a Core Image color.

So in this case, _color is not being initialized with a Core Image color. You can see that this is true because even just [_color CIColor] throws an error.

Your other case works because you initialize a whole new CIColor with a the CGColor property of _color, which from the documentation always resolves to a CGColor. So, in the other case, the CIColor is successfully created and you can call stringRepresentation on it.