I have an NSArray filled with bools (expressed as a number), and I need to test to see if any object within the array is equal to 1. How can I do it?
BOOLs are not objects. Assuming you mean some object representing a boolean like NSNumber that implements a proper isEqual:
, you could just do something like [array containsObject:[NSNumber numberWithBool:YES]]
.
As Chuck says, use -[NSArray containsObject:[NSNumber numberWithBool:YES]]
. As a thought experiment, here are some other ways to accomplish the goal...
You can do this using an 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 coding, though I'm not sure of its relative efficiency:
[[myArray valueForKeyPath:@"@sum.boolValue"] integerValue] > 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With