I have a mutable array of Boolean values and I want to check to see if ANY of the values are YES.
At present I am creating another array alongside this one which is always ALL False like so;
[MyArray addObject:[NSNumber numberWithBool:switchInput]];
[MyAllNoArray addObject:[NSNumber numberWithBool:NO]];
The user does some bits and the some of the objects in MyArray may become YES, I then use the below to see if ANY are true or not.
if([MyArray isEqualToArray:MyAllNoArray])
I am just wondering if there is a better way (this way seems wasteful)?
I have thought about a counter, each time one of the objects changes the counter goes up or down (depending on changing to YES or NO), if the counter is 0 then so is the array. But I am just thinking there may be a better way within an IF statement that I am missing.
I think a simpler solution would be this:
NSArray *bools = @[@(NO),@(NO), @(YES)];
if ([bools containsObject:@(YES)]) {
// do your magic here
}
Loops and blocks would be an overkill if you just need to check for presence.
NSArray *myArray;
__block bool hasTrue = NO;
[myArray enumerateObjectsUsingBlock:^(NSNumber *num, NSUInteger idx, BOOL *stop) {
if (num.boolValue) {
hasTrue = YES;
*stop = YES;
}
}];
if (hasTrue)
NSLog(@"there is a true value in myArray.");
else
NSLog(@"there is not true value in myArray.");
Or turn it into a method:
- (BOOL)doesMyArrayHaveTrue {
NSArray *myArray;
__block bool hasTrue = NO;
[myArray enumerateObjectsUsingBlock:^(NSNumber *num, NSUInteger idx, BOOL *stop) {
if (num.boolValue) {
hasTrue = YES;
*stop = YES;
}
}];
return hasTrue;
}
Or...I haven't tried this yet but I think it should work:
NSNumber * max = [myArray valueForKeyPath:@"@max.self"];
if (max.boolValue)
NSLog(@"there is a true values.");
else
NSLog(@"there is not a true value.");
The easiest way is to use containsObject:@(YES)
.
Explanation
If you check the NSArray documentation it says
containsObject: Returns a Boolean value that indicates whether a given object is present in the array.
- (BOOL)containsObject:(id)anObject
Discussion
This method determines whether anObject is present in the array by sending an isEqual: message to each of the array’s objects (and passing anObject as the parameter to each isEqual: message).
So containsObject:@(YES)
should do the trick
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