简体   繁体   English

For循环和if语句

[英]For loop and if statement

I am working with the following for loop: 我正在使用以下for循环:

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

I have a if/else statement under the for loop, in which the else block shows an alert message. 我在for循环下有一个if / else语句,其中else块显示了一条警告消息。 Suppose array count is 10; 假设数组计数为10; then when the if fails, the else block will execute ten times, and the alert message displays ten times. 然后, if失败,则else块将执行十次,并且警告消息将显示十次。 How can I deactivate this? 如何停用此功能?

Your problem is a general programing problem. 您的问题是一般的编程问题。 The simplest way is to just use a BOOL flag. 最简单的方法是仅使用BOOL标志。

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

If you want to show only one alert in case of failed condition that would probably mean you don't want to continue the loop. 如果您只想在发生故障的情况下仅显示一个警报,则可能意味着您不想继续循环。 So as Jason Coco mentioned in his comment, you break from the loop. 因此,正如Jason Coco在他的评论中提到的那样,您break了循环。 Here's a simple example on how to do this: 这是有关如何执行此操作的简单示例:

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

Otherwise, if you want to check some condition for every element of the array, you would probably want to keep track of failures and show user the summary (could be an alert message, another view, etc). 否则,如果您要检查阵列中每个元素的某些状况,则可能要跟踪失败并向用户显示摘要(可能是警报消息,其他视图等)。 Short example: 简短示例:

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];

Good luck! 祝好运!

Assume C is an Array where n is an int or NSNumber type caste to int 假设C是一个数组,其中n是一个int或NSNumber类型的等级转换为int

for(n in C){ for(n in C){

if{n equal to 10) 如果{n等于10)

dostuff } 做东西 }

else{ doOtherStuff } } else {doOtherStuff}}

} }

The good thing about this approach you can inore the size of the Array. 关于这种方法的好处是,您可以设置数组的大小。

Look at the docs for Enumeration Glass 查看Enumeration Glass的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM