I am working with the following for loop:
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. Suppose array count is 10; then when the if
fails开发者_Python百科, the else
block will execute ten times, and the alert message displays ten times. How can I deactivate this?
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;
}
}
}
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!
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
精彩评论