简体   繁体   中英

Checking if array contains two objects

I'm attempting to implement the containsObject but with two parameters, is this possible?

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. 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. (You can read its official documentation here ) To fix your problem, use the && operator and call containsObject on each object individually.

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. Other answers detail this approach.

If you have large arrays and many comparisons to perform, NSSet may be better suited for your task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM