2011-02-07 50 views
0

嗨,我只想知道這是否正確,我們可以檢查零這種方式 - if(self.spinner==nil)是否檢查零值這種方式是正確的?

感謝

if (self.spinner == nil) { 
    self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; 
    //.............needs work............. 
    CGRect center = [self.view bounds]; 
    CGSize winCenter = center.size; 
    CGPoint pont = CGPointMake(winCenter.width/2,winCenter.height/2); 
    //CGPoint pont = CGPointMake(10,40); 
    [spinner setCenter:pont]; 
    [self.view addSubview:spinner]; 
    [self.spinner startAnimating]; 
} else { 
    [self.spinner startAnimating]; 
} 

回答

0

是,檢查,對nil是絕對有效的。在標頭深處,nil定義爲(id)0,這意味着您可以使用指針相等性將其與任何Objective-C對象進行比較。

精明的觀察者將意識到的是,由於nil是零,並且目標C的條件的控制結構(ifwhile等)接受任何int樣的數據類型,使用一個對象的指針作爲條件本身將通過如果對象是非nil和失敗,如果對象是nil

if (self.spinner) // implicitly checks that self.spinner is non-nil 
if (!self.spinner) // implicitly checks that self.spinner is nil 

根據您的背景程序員,你可能會或可能不會喜歡這個功能。但它的工作原理與nil相同。

2

是的,它是正確的。你甚至可以寫出更短:

if (!self.spinner) { 
... 
} 
2

是的,但我想稍微改變它:

if (!self.spinner) { 
    self.spinner = [[UIActivityIndicatorView alloc] ... 
    ... 
} 
// Do this outside the test, thus avoiding the else. 
[self.spinner startAnimating]; 
相關問題