There’s a handy method in the NSArray class that lets us check if an array contains a particular object or not. The containsObject method returns a BOOL for us to evaluate.
Consider this:
1 2 3 4 5 6 7 |
// create an array NSArray *array = @[@"Apples", @"Pears" , @"Bananas"]; // check if Pears are in the array if ([array containsObject:@"Pears"]) { NSLog(@"We have Pears."); } |
Likewise, we can check if our array does not contain a particular object by testing the opposite:
1 2 3 4 |
// check if Grapes are not in the array if (![array containsObject:@"Grapes"]) { NSLog(@"But we don't have Grapes."); } |
Both the NSMutableArray and NSSet classes has the same method, so we can check for the (un-)presence of our objects in mutable arrays and sets the same way.