7

I'm trying to determine if two colors are equivalent, using code written in Objective-C.

I'm using this snippet of code to determine if the two colors are equivalent (currently for debugging purposes)

    NSLog(@"currentColor is %@", currentColor);
NSLog(@"Adjacent Color is %@",[[buttonArray objectAtIndex:1] backgroundColor]);
NSLog(@"%i",[[buttonArray objectAtIndex:1] backgroundColor]==currentColor);

My console is showing

2009-10-20 00:27:10.814 colorGame[13588:207] currentColor is kCGColorSpaceModelRGB 0 0 1 1 
2009-10-20 00:27:10.815 colorGame[13588:207] Adjacent Color is kCGColorSpaceModelRGB 0 0 1 1 
2009-10-20 00:27:10.815 colorGame[13588:207] 0

I can post more code if asked (I don't know if any more is really necessary). Current color was initially defined as

UIColor *currentColor;

if that is any help.

I'm fairly sure I'm just doing the compare wrong, and that there is probably some built-in method that can compare colors, that I'm just not aware of.

Justin Boo
  • 10,132
  • 8
  • 50
  • 71
sshaukat
  • 71
  • 1
  • 2
  • The question should be rephrased to "Comparing objects in Objective-C" since it turns out it has nothing to do with colors. – nschmidt Oct 20 '09 at 07:44

3 Answers3

19
@implementation UIColor (compare)

- (BOOL) isEqualToColor:(UIColor *) otherColor
{
return CGColorEqualToColor(self.CGColor, otherColor.CGColor);
}

@end

Keep in mind that two colors that look the same may or may not return TRUE, since the components are kept as floats and they may differ by a value that's less than the display hardware can resolve.

Also keep in mind that if they're defined in different color spaces, this method will never return TRUE.

NSResponder
  • 16,861
  • 7
  • 32
  • 46
  • I just had a situation where two UIColors had the same value components and were in the same color space but CGColorEqualToColor returned not equal while [UIColor isEqual:] worked, is there something I'm missing? – yo.ian.g Apr 27 '14 at 18:16
11

objects must be compared using the isEqual: method, not ==, which simply compares the pointer address

newacct
  • 119,665
  • 29
  • 163
  • 224
  • THANK YOU! I just modified my code a bit to compare the string outputs as opposed to the colors themselves, using isEqual along the way. Works beautifully now. Thanks! – sshaukat Oct 20 '09 at 07:46
1

You're testing object pointers for equivalency, which is probably never going to return true. If you want to work with the actual color values then you'll need to get the underlying CGColor reference.

Azeem.Butt
  • 5,855
  • 1
  • 26
  • 22