For loop and if statement

后端 未结 3 486
耶瑟儿~
耶瑟儿~ 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!

    0 讨论(0)
  • 2021-01-17 06:39

    Assume C is an Array where n is an int or NSNumber type caste to int

    for(n in C){

    if{n equal to 10)

    dostuff }

    else{ doOtherStuff } }

    }

    The good thing about this approach you can inore the size of the Array.

    Look at the docs for Enumeration Glass

    0 讨论(0)
  • 2021-01-17 06:47

    Your problem is a general programing problem. The simplest way is to just use a BOOL flag.

    BOOL alertShown = NO;
    for (int intPrjName = 0; intPrjName < [arrPrjName count]; intPrjName++) {
        if (something) {
            // . . .
        } else {
            if (!alertShown) {
                [self showAlert:intPrjName]; // Or something
                alertShown = YES;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题