Home > Enterprise >  How will I check a NSInteger is in a NSMutableArray?
How will I check a NSInteger is in a NSMutableArray?

Time:04-06

I am adding NSInteger object as NSNumber in a NSMutableArray. But now I am such in condition like that I need to check a NSInteger is in the NSMutableArray. If the array contains the value then I will execute my next code else I will execute other code. I want to execute else condition only if array doesn't contain the value. I tried this code:

for(int i=0; i<self.indexArray.count; i  ){
   if([[self.indexArray objectAtIndex:i] integerValue]==self.selectedIndex){
       NSLog(@"execute if in the array");
    }
   else{
       NSLog(@"execute if not in the array");
   }
}

Though the array contains the value, else is executing for the loop. My question is how will I check a value which one is in a NSMutableArray or not.

CodePudding user response:

This is the simple solution:

BOOL containsSelected = NO;

for (int i = 0; i < self.indexArray.count; i  ){
   if ([[self.indexArray objectAtIndex:i] integerValue] == self.selectedIndex){
       containsSelected = YES;
       break;
   }
}

if (containsSelected) {
    NSLog(@"execute if in the array");
} else {
    NSLog(@"execute if not in the array");
}

I believe this could be further simplifed to:

if ([self.indexArray containsObject:@(self.selectedIndex)]) {
    NSLog(@"execute if in the array");
} else {
    NSLog(@"execute if not in the array");
}

but I haven't tested it.

  • Related