NSArray populated with bool objects

I have an NSArray filled with bools (expressed as a number) and I need to check if there is any object in the array equal to 1. How can I do this?

+6
cocoa boolean nsarray
source share
2 answers

BOOL are not objects. Assuming you mean some kind of object representing the logical type NSNumber that implements the correct isEqual: you can just do something like [array containsObject:[NSNumber numberWithBool:YES]] .

+12
source share

As Chuck says, use -[NSArray containsObject:[NSNumber numberWithBool:YES]] . As a thought experiment, here are some other ways to achieve your goal ...

You can do this using NSPredicate or using the new blocks API:

 NSArray *myArr //decleared, initialized and filled BOOL anyTrue = [myArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"boolValue == 1"]].count > 0; 

or

 BOOL anyTrue = [myArray indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) { if([obj boolValue]) { *stop = YES; } return [obj boolValue]; }].count > 0; 

You can also use Key-Value encoding, although I'm not sure about its relative effectiveness:

 [[myArray valueForKeyPath:@"@sum.boolValue"] integerValue] > 0; 
+6
source share

All Articles