为什么关于UIColor whiteColor的声明评估为false?

Ben*_*Ben 2 iphone xcode objective-c

只是测试一下......当我摇动它时,我试图让我的视图的背景颜色切换....但只有当它是当前的某种颜色.

-(void)viewDidLoad{    
    self.view.backgroundColor = [UIColor whiteColor];
}


-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{       
    if(event.subtype == UIEventSubtypeMotionShake)
    {
        [self switchBackground];
    }
}


-(void)switchBackground{        
//I can't get the if statement below to evaluate to true - UIColor whiteColor is
// returning something I don't understand or maybe self.view.backgroundColor 
//is not the right property to be referencing?

    if (self.view.backgroundColor == [UIColor whiteColor]){

        self.view.backgroundColor = [UIColor blackColor];
    }    
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*mir 5

您在这里比较指针,而不是颜色值.使用-isEqual方法进行对象比较:

if ([self.view.backgroundColor isEqual:[UIColor whiteColor]])
   ...
Run Code Online (Sandbox Code Playgroud)

请注意,视图的backgroundColor属性是使用copy属性定义的,因此它不会保留指向颜色对象的指针.但是,以下简单示例将起作用:

UIColor* white1 = [UIColor whiteColor];
if (white1 == [UIColor whiteColor])
    DLogFunction(@"White"); // Prints
Run Code Online (Sandbox Code Playgroud)