Krish
Krish

Reputation: 4232

How to find If array contains two or more objects

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

Currently I've got:

and apparently there's too many arguments. I've delved through Apple's docs but I'm yet to find anything. Any suggestions?

if ([ myArray containsObject:@"1", @"2"]){
    NSLog(@"if");
} else if([ myArray containsObject:@"1", @"2",@"3",@"4"]) {
   NSLog(@"else if");
}else if([ myArray containsObject:@"1", @"2",@"3"]) {
   NSLog(@"else");
}

myArray:-

myArray is (
    1,
    2,
    3,
    4
)

Upvotes: 0

Views: 90

Answers (3)

Muhammad Adnan
Muhammad Adnan

Reputation: 2668

you can check subsets of array

 NSArray *arry1= [NSArray arrayWithObjects:@"1",@"2",@"3",@"4", nil];
        NSArray *arry2= [NSArray arrayWithObjects:@"1",@"2", nil];

        NSSet *set1 = [NSSet setWithArray:arry1];
        NSSet *set2 = [NSSet setWithArray:arry2];

        if ([set2 isSubsetOfSet:set1])
        {
            NSLog(@"array1 contains all elements of array 2");
        }else{
            NSLog(@"array1 does not contains all elements of array 2");
        }

Upvotes: 1

Gandalf
Gandalf

Reputation: 2417

You need to write your own custom code. Pass all the required objects in method as an array and iterate over the array of all objects. If any object is not found, return false.

-(BOOL)containsObjects:(NSArray*)arrObj
{
    BOOL result = YES;
    for(CustomObject *cObj in arrObj) {
        result = [mainArray containsObject:cObj];
        if(result == NO) {
            break;
        }
    }

    return result;
}

Upvotes: 0

Witterquick
Witterquick

Reputation: 6150

if ([myArray containsObject:@"1"] || [ myArray containsObject: @"2"]) {
    NSLog(@"if");
} else {
   NSLog(@"else");
}

Upvotes: 0

Related Questions