在Objective-C中,检查一个布尔值数组,看看是否至少有一个是YES

时间:2021-12-07 09:59:55

I have a mutable array of Boolean values and I want to check to see if ANY of the values are YES.

我有一个布尔值的可变数组,我想检查其中是否有值为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.

用户执行一些位,MyArray中的一些对象可能会变成YES,然后我使用下面的代码来查看它们是否为真。

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.

我已经考虑过一个计数器,每次一个对象改变计数器上或下(取决于变化到是或否),如果计数器是0,那么数组也是。但我只是在想,在一个IF语句中,或许有更好的方式来表达我的想法。

6 个解决方案

#1


10  

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.

如果您只需要检查是否存在,那么循环和块将是一个超杀。

#2


1  

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.");

#3


1  

The easiest way is to use containsObject:@(YES).

最简单的方法是使用containsObject:@(是的)。

Explanation

解释

If you check the NSArray documentation it says

如果你检查NSArray文档,它说

containsObject: Returns a Boolean value that indicates whether a given object is present in the array.

containsObject:返回一个布尔值,该值指示数组中是否存在给定的对象。

  • (BOOL)containsObject:(id)anObject
  • (保龄球)containsObject:anObject(id)

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

该方法通过向数组的每个对象发送一个isEqual:消息(并将一个对象作为参数传递给每个isEqual: message)来确定数组中是否存在一个对象。

So containsObject:@(YES) should do the trick

所以containsObject:@(是的)应该很管用

#4


0  

Pretty much the same answer as random, but without blocks.

几乎和随机答案一样,但是没有块。

bool allFalse = true;
for(NSNumber *number in MyArray)
{
    if([number boolValue])
    {
        allFalse = false;
        break;
    }
}

if(!allFalse)
{
    ...
}

#5


0  

NSNumber* yesBool = [NSNumber numberWithBool:YES];
BOOL foundYes = NO;
for (NSNumber* num in MyArray) {
    if ([num isEqualToNumber:yesBool) {
        foundYes = YES;
        break;
    }
}

You can't do much (*) better than that for a test without some sort of "score", though your counter scheme is no doubt better, should you choose to "keep score".

如果没有某种“分数”,你不可能比考试做得更好(*),尽管你的反计分方案无疑是更好的,如果你选择“保持分数”的话。

(*) It's debatable whether using isEqualToNumber is more or less efficient than simply testing boolValue.

(*)使用isEqualToNumber是否比简单地测试boolValue效率更高或更低是有争议的。

#6


0  

Many good answers here, and @Arcanfel and @rr1g0's suggestion of simply using containsObject: is really elegant and simple.

这里有很多很好的答案,@Arcanfel和@rr1g0关于简单使用containsObject:的建议非常优雅和简单。

The many esteemed colleagues who have answered the thread have left out an important option, though - a predicate-based solution. So here goes, in the interest of completeness:

尽管许多受人尊敬的同事已经回答了这个问题,但他们还是忽略了一个重要的选项——基于谓词的解决方案。因此,为了完整起见

NSArray *data = @[@(NO), @(YES), @(NO)];

NSPredicate *hasYesPred = [NSPredicate predicateWithFormat: @"SUBQUERY(SELF, $s, $s == %@).@count > 0", @(YES)];

BOOL hasYes = [hasYesPred evaluateWithObject: data];

The idea here is that the subquery constructs an array of objects that are equal to @(YES), then we take the count of that, and if it is positive, we know that there is at least one true boolean value in the array.

这里的想法是,子查询构造了一个对象数组,这些对象等于@(YES),然后我们对其进行计数,如果它是正数,我们知道数组中至少有一个真正的布尔值。

This approach obviously can be extended to other types of numbers - to determine if there is at least one negative number in an array, for instance.

这种方法显然可以扩展到其他类型的数字——例如,确定数组中是否至少有一个负数。

#1


10  

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.

如果您只需要检查是否存在,那么循环和块将是一个超杀。

#2


1  

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.");

#3


1  

The easiest way is to use containsObject:@(YES).

最简单的方法是使用containsObject:@(是的)。

Explanation

解释

If you check the NSArray documentation it says

如果你检查NSArray文档,它说

containsObject: Returns a Boolean value that indicates whether a given object is present in the array.

containsObject:返回一个布尔值,该值指示数组中是否存在给定的对象。

  • (BOOL)containsObject:(id)anObject
  • (保龄球)containsObject:anObject(id)

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

该方法通过向数组的每个对象发送一个isEqual:消息(并将一个对象作为参数传递给每个isEqual: message)来确定数组中是否存在一个对象。

So containsObject:@(YES) should do the trick

所以containsObject:@(是的)应该很管用

#4


0  

Pretty much the same answer as random, but without blocks.

几乎和随机答案一样,但是没有块。

bool allFalse = true;
for(NSNumber *number in MyArray)
{
    if([number boolValue])
    {
        allFalse = false;
        break;
    }
}

if(!allFalse)
{
    ...
}

#5


0  

NSNumber* yesBool = [NSNumber numberWithBool:YES];
BOOL foundYes = NO;
for (NSNumber* num in MyArray) {
    if ([num isEqualToNumber:yesBool) {
        foundYes = YES;
        break;
    }
}

You can't do much (*) better than that for a test without some sort of "score", though your counter scheme is no doubt better, should you choose to "keep score".

如果没有某种“分数”,你不可能比考试做得更好(*),尽管你的反计分方案无疑是更好的,如果你选择“保持分数”的话。

(*) It's debatable whether using isEqualToNumber is more or less efficient than simply testing boolValue.

(*)使用isEqualToNumber是否比简单地测试boolValue效率更高或更低是有争议的。

#6


0  

Many good answers here, and @Arcanfel and @rr1g0's suggestion of simply using containsObject: is really elegant and simple.

这里有很多很好的答案,@Arcanfel和@rr1g0关于简单使用containsObject:的建议非常优雅和简单。

The many esteemed colleagues who have answered the thread have left out an important option, though - a predicate-based solution. So here goes, in the interest of completeness:

尽管许多受人尊敬的同事已经回答了这个问题,但他们还是忽略了一个重要的选项——基于谓词的解决方案。因此,为了完整起见

NSArray *data = @[@(NO), @(YES), @(NO)];

NSPredicate *hasYesPred = [NSPredicate predicateWithFormat: @"SUBQUERY(SELF, $s, $s == %@).@count > 0", @(YES)];

BOOL hasYes = [hasYesPred evaluateWithObject: data];

The idea here is that the subquery constructs an array of objects that are equal to @(YES), then we take the count of that, and if it is positive, we know that there is at least one true boolean value in the array.

这里的想法是,子查询构造了一个对象数组,这些对象等于@(YES),然后我们对其进行计数,如果它是正数,我们知道数组中至少有一个真正的布尔值。

This approach obviously can be extended to other types of numbers - to determine if there is at least one negative number in an array, for instance.

这种方法显然可以扩展到其他类型的数字——例如,确定数组中是否至少有一个负数。