2010-11-12 62 views
0

我知道,一旦你在編碼方面做得更好,就會知道變量是什麼,並且空出現在這裏或那裏可能不會發生。在這種心態的方式中,是否有任何方法來使你的變量聲稱爲空,並確認它爲空,或者你只是使用錯誤的代碼?從零開始反向工作

例子:

-(IBAction) startMotion: (id)sender { 
    NSLog(@"Forward or back button is being pressed."); 
    UIButton * buttonName = (UIButton *) sender; 
    NSLog(@"Button Name: %@", buttonName.currentTitle); 
} 

按鈕名稱:(空)是在控制檯中顯示的內容

感謝

+1

這是......客觀C?您應該將目標語言添加到標籤中,以便最好地瞭解該語言的人可以爲您提供幫助。 – 2010-11-12 19:23:57

回答

1

According to Apple's docs, the value for currentTitle may be nil.它可能只是沒有設置。

你總是可以做if (myObject == nil)檢查,或者在這種情況下:

-(IBAction) startMotion: (id)sender { 
    NSLog(@"Forward or back button is being pressed."); 
    UIButton * buttonName = (UIButton *) sender; 
    if (buttonName != nil) { 
    NSString *title = buttonName.currentTitle; 
    NSLog(@"Button Name: %@", title); 
    } 
} 

另一種方法來檢查,如果按下後退或前進按鈕,就是檢查id本身。

//in the interface, and connect it up in IB 
//IBOutlet UIButton *fwdButton; 
//IBOutlet UIButton *bckButton; 

-(IBAction) startMotion: (id)sender { 
    NSLog(@"Forward or back button is being pressed."); 
    UIButton * buttonName = (UIButton *) sender; 
    if (buttonName == fwdButton) { 
    NSLog(@"FWD Button"); 
    } 

    if (buttonName == bckButton) { 
    NSLog(@"BCK Button"); 
    } 
} 

此外,請確保您的網點和操作都在IB中連接,並保存並重新構建項目。我已經去了我在IB改變過的地方,保存了.m文件(不是筆尖),並且像「爲什麼這不起作用?」

-3

buttonName不能爲空,否則將buttonName.currentTitle產生錯誤。因此currentTitle屬性本身必須爲空。

或者,也許currentTitle是值爲(null)的字符串。

通常,在Objective-C中,如果您有[[[myObject aMethod] anotherMethod] xyz]且結果爲null很難知道哪個方法返回null。但是使用點語法.並非如此。

+2

錯誤。 'buttonName.currentTitle'只是寫['buttonName currentTitle]'的一種不同的方式,這只是一個發送沒有任何參數的消息的不同語法。既然你可以安全地發送一個消息給'nil'(然後返回'nil'或者0或者0.0或者'NULL'),'buttonName'也可以是'nil'。 – Sven 2010-11-12 19:50:01

0

我在界面生成器中使用了錯誤的字段我從界面生成器標識中使用名稱而不是按鈕設置中的標題。