Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray filled with bool objects

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?

like image 287
Matt S. Avatar asked May 04 '10 22:05

Matt S.


2 Answers

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]].

like image 99
Chuck Avatar answered Sep 20 '22 15:09

Chuck


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;
like image 39
Barry Wark Avatar answered Sep 22 '22 15:09

Barry Wark