0

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?

unom
  • 11,438
  • 4
  • 34
  • 54

1 Answers1

0

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.

Carter
  • 3,053
  • 1
  • 17
  • 22
  • _color is set to [UIColor blackColor], you mean to say this is not enough and I need to initialize the CIColor property too? – unom Aug 09 '16 at 13:17
  • No, the property is readonly, you can't initialize it. The documentation says the _UIColor_ _object_ must be initialized with a Core Image color. This means that you should set `_color` to `[UIColor colorWithCIColor:Some_CIColor]` or, in your other case, `CGColor` works as well. – Carter Aug 09 '16 at 15:41
  • So if I initialize _color = [UIColor blackColor] it is not enough to a be able to use the CIColor property? – unom Aug 11 '16 at 06:15
  • No, it is not. The documentation states that it is a requirement that the UIColor object be initialized with a Core Image color object if you want to access the CIColor property. There's no reason given, but it's probably related to how the color is represented in the underlying data structure. [This StackOverflow question](http://stackoverflow.com/questions/38888709/uicolor-and-cicolor-how-do-they-compare-and-what-is-the-purpose-of-having-two-of) goes into more detail. – Carter Aug 11 '16 at 08:04