The reason it doesn't work is that UIView
's backgroundColor
is a copy
property. It's declared like this:
@property(nonatomic, copy) UIColor *backgroundColor;
That means that when the color object that you get from [UIColor redColor]
is set as the backgroundColor
, the whole object is copied, and the copy retained by the UIView
will be on a different memory address than the one retained by the UIColor
class object.
==
checks if the pointers are the same, which means that it will succeed only if the two pointers point to the very same object. This is what you want to do sometimes. For example:
if ([aView superView] == self)
[aView removeFromSuperview];
Here, you want to be sure that aView
's super view is actually this very object, not just one that is "the same" according to some criteria.
But when you compare two strings, you are (almost always) interested in whether they contain the same characters, and it doesn't matter whether they are on different memory addresses. Thus you use:
if ([aString isEqualToString:anotherString]) // faster than isEqual:
And in our example with the colors, it's the same: we want to know whether the two objects both represent a red color, not whether the two pointers point to the exact same object.
If the backgroundColor
property was declared as retain
you could have used ==
, and it would have worked until UIColor
for some reason reallocated its redColor
object. That's not likely to happen, but it's to underscore that the object represents a unique thing that objects like strings and colors are usually copied
rather than ´retained´. There can be only one color red, and there can be only one string that containing the characters "Hello world!". So it comes down to a metaphysical argument in the end.