[英]Checking if array contains two objects
I'm attempting to implement the containsObject but with two parameters, is this possible? 我正在尝试实现带有两个参数的containsObject,这可能吗?
Currently I've got: 目前我有:
if ([ myArray containsObject:@"Object1", @"Object2"]){
return result;
} else {
return NO;
}
and apparently there's too many arguments. 显然有太多的争论。 I've delved through Apple's docs but I'm yet to find anything. 我已经研究过Apple的文档,但还没有找到任何东西。 Any suggestions? 有什么建议么?
Why not just do this? 为什么不这样做呢?
if ([ myArray containsObject:@"Object1" ] && [ myArray containsObject:@"Object 2" ] ){
return result;
} else {
return NO;
}
There is too many arguments, containsObject is for a single object. 有太多的争论,containsObject是针对单个对象。 (You can read its official documentation here ) To fix your problem, use the &&
operator and call containsObject on each object individually. (您可以在此处阅读其官方文档)要解决问题,请使用&&
运算符,并分别对每个对象调用containsObject。
if ([myArray containsObject:@"Object1"] && [myArray containsObject@"Object2"]){
return result;
} else {
return NO;
}
You will have to evaluate them individually. 您将不得不分别评估它们。 Example: 例:
bool MONNSArrayContainsAllObjectsIn(NSArray* const pArray, NSArray* const pSought) {
assert(pArray);
assert(pSought);
assert(0 < pSought.count);
for (id at in pSought) {
if (false == [pArray containsObject:at]) {
return false;
}
}
return true;
}
Then your code above becomes: 然后,上面的代码变为:
return MONNSArrayContainsAllObjectsIn(myArray, @[@"Object1", @"Object2"]);
If you are working with a known number of elements (2 in this case), then you can avoid creating the temporary array -- if you prefer to make that optimization and write out all variants you need, including parameters. 如果您正在使用已知数量的元素(在这种情况下为2),则可以避免创建临时数组-如果您希望进行优化并写出所需的所有变体(包括参数)。 Other answers detail this approach. 其他答案详细介绍了这种方法。
If you have large arrays and many comparisons to perform, NSSet
may be better suited for your task. 如果要执行的数组很大且有许多比较,则NSSet
可能更适合您的任务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.