簡體   English   中英

For循環和if語句

[英]For loop and if statement

我正在使用以下for循環:

for (int intPrjName = 0; intPrjName < [arrPrjName count]; intPrjName++)

我在for循環下有一個if / else語句,其中else塊顯示了一條警告消息。 假設數組計數為10; 然后, if失敗,則else塊將執行十次,並且警告消息將顯示十次。 如何停用此功能?

您的問題是一般的編程問題。 最簡單的方法是僅使用BOOL標志。

BOOL alertShown = NO;
for (int intPrjName = 0; intPrjName < [arrPrjName count]; intPrjName++) {
    if (something) {
        // . . .
    } else {
        if (!alertShown) {
            [self showAlert:intPrjName]; // Or something
            alertShown = YES;
        }
    }
}

如果您只想在發生故障的情況下僅顯示一個警報,則可能意味着您不想繼續循環。 因此,正如Jason Coco在他的評論中提到的那樣,您break了循環。 這是有關如何執行此操作的簡單示例:

for (int intPrjName = 0; intPrjName < [arrPrjName count]; intPrjName++) {
   if (condition) {
      // do something
   } else {
      break;
   }
}

否則,如果您要檢查陣列中每個元素的某些狀況,則可能要跟蹤失敗並向用戶顯示摘要(可能是警報消息,其他視圖等)。 簡短示例:

NSUInteger numFailures = 0;

for (int intPrjName = 0; intPrjName < [arrPrjName count]; intPrjName++) {
   if (condition) {
      // do something
   } else {
      numFailures++;
   }
}

UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:title
                  message:@"Operation failed: %d", numFailures
                  delegate:nil
                  cancelButtonTitle:@"OK"
                  otherButtonTitles:nil] autorelease];
[alert show];

祝好運!

假設C是一個數組,其中n是一個int或NSNumber類型的等級轉換為int

for(n in C){

如果{n等於10)

做東西 }

else {doOtherStuff}}

}

關於這種方法的好處是,您可以設置數組的大小。

查看Enumeration Glass的文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM