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?
+5
A:
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]]
.
Chuck
2010-05-04 22:47:12
wow. I didn't know it could be used like that. Thanks!!!
Matt S.
2010-05-04 22:52:35
+5
A:
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;
Barry Wark
2010-05-04 22:52:42
@Chuck, yes, I'd be just a little peeved to have to read any of these solutions in real code. Fun little functional programming brain exercise, though.
Barry Wark
2010-05-05 19:26:45