For loop and if statement

后端 未结 3 509
耶瑟儿~
耶瑟儿~ 2021-01-17 06:22

I am working with the following for loop:

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

I have a if/else stat

3条回答
  •  死守一世寂寞
    2021-01-17 06:37

    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. 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!

提交回复
热议问题