Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Objective-C Check an array of Boolean Values and see if at least ONE is YES

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.

like image 649
Recycled Steel Avatar asked Sep 04 '13 16:09

Recycled Steel


3 Answers

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.

like image 147
Arthur Shinkevich Avatar answered Nov 14 '22 23:11

Arthur Shinkevich


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.");
like image 44
random Avatar answered Nov 14 '22 22:11

random


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

like image 45
rr1g0 Avatar answered Nov 14 '22 23:11

rr1g0