2012-05-05 38 views
-4

如果發生兩件事情之一,有沒有辦法執行一個代碼?具體來說,我有2個TextFields,如果其中任何一個是空的,我想在執行操作時彈出UIAlertView。我可以設置我可以有一個if /或聲明嗎?

if ([myTextField.text length] == 0) { 
    NSLog(@"Nothing There"); 
    UIAlertView *nothing = [[UIAlertView alloc] initWithTitle:@"Incomplete" message:@"Please fill out all fields before recording" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil]; 
    [nothing show]; 
    [nothing release]; 
} 
if ([yourTextField.text length] == 0) { 
    NSLog(@"Nothing For Name"); 
    UIAlertView *nothing = [[UIAlertView alloc] initWithTitle:@"Incomplete" message:@"Please fill out all fields before recording" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil]; 
    [nothing show]; 
    [nothing release]; 
} 

但是如果兩者都是空的,則會彈出語句兩次。

如何獲得它只彈出一次,如果其中之一或兩者都是空的?

+0

嘿@AshBurlaczenko如果你沒有添加任何東西,那麼不要評論。你即將被標記 – user717452

+2

@ AshBurlaczenko的評論在這種情況下是正確的。您在Objective-C中詢問最常用的BASIC語言語法。有關Objective-C的快速教程可能會對您有所幫助,但您可以隨時就您在SO上可能遇到的任何疑問提出問題。 –

+2

@ user717452,你給我評論的標記是什麼原因?答案是一個非常基本的編程概念,雖然語法可能會因不同的語言而有所不同,但通過了解基本知識,您可以通過谷歌輕鬆找到答案。我從來沒有編寫Objective-C程序,但我知道答案,因爲我瞭解基礎知識。 –

回答

2

您可以將兩個條件結合成使用||(或)經營者的單一if聲明。

if (([myTextField.text length] == 0) || ([yourTextField.text length] == 0)) { 
    NSLog(@"Nothing There"); 
    UIAlertView *nothing = [[UIAlertView alloc] initWithTitle:@"Incomplete" 
                 message:@"Please fill out all fields before recording" 
                delegate:self 
              cancelButtonTitle:@"Ok" 
              otherButtonTitles:nil]; 
    [nothing show]; 
    [nothing release]; 
} 
0

使用複合條件

if (([myTextField.text length] == 0) || ([yourTextField.text length] == 0))) { 
    NSLog(@"Nothing There"); 
    UIAlertView *nothing = [[UIAlertView alloc] initWithTitle:@"Incomplete" message:@"Please fill out all fields before recording" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil]; 
    [nothing show]; 
    [nothing release]; 
} 
0

至於其他的答案指出,你可以做一個或懶惰的評價是這樣的:

if ([myTextField.text length] == 0 || [yourTextField.text length] == 0) { 

懶惰評價(的||代替|)只是確保第二個條件是隻運行,如果它一定要是。

請注意,這些事情評估BOOL,所以你可以利用和給的東西的名字。例如:

BOOL eitherFieldZeroLength = ([myTextField.text length] == 0 || [yourTextField.text length] == 0); 
if (eitherFieldZeroLength) { 

雖然這對目前的情況來說是微不足道的,但使用中間變量可以爲您的代碼增加清晰度。

+3

邏輯或「||」並不是按位或「|」的懶惰版本,只是當您按照您的建議使用它們時,它們似乎就像那樣工作。邏輯或正在比較真值和假值,而他們按位或將各個位組合在一起。 – mttrb

+0

@mttrb我很樂意糾正或刪除我的答案,一旦我得到這個。但是,你的意思是什麼?這些不是短路評估? http://en.wikipedia.org/wiki/Short-circuit_evaluation此外,你是什麼意思,他們「似乎像那樣工作?」他們這樣工作,對吧? –

相關問題