get iphone window background color
I've been looking at the Stanford University iphone videos on iTunes U. And saw the teacher trying to do something similar to this code but he realised and said it didn't work though I didn't get why:
- (IBAction)flashPressed{
if (window.backgroundColor == [UIColor magentaColor]){
window.backgroundColor = [UIColor redColor];
}else {
window.backgroundColor = [UIColor magentaColor];
}开发者_如何学JAVA
}
Objective-C, windows based application. Not sure what else you need to know.
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.
To check if two UIColors are equal, use the isEqual: message instead of the == operator.
if ([window.backgroundColor isEqual:[UIColor redColor]]) {
NSLog(@"Yup, it's red");
} else {
NSLog(@"OMG, it's not red!");
}
// result --> Yup, it's red
That's a general pattern for comparing objects rather than using == like you do for primitives like ints or floats. NSString works the same way.
Too much information section:
The pattern for objects that have a defined order is to give them a compare: method that returns a NSSortDescriptor.
精彩评论