Check that the contents of one NSArray are all in

2020-02-06 03:11发布

I have one NSArray with names in string objects like this:@[@"john", @"smith", @"alex", @"louis"], and I have another array that contains lots of names. How can I check that all the objects in the first array are in the second?

9条回答
来,给爷笑一个
2楼-- · 2020-02-06 03:39

NSSet has the functionality that you are looking for.

If we disregard performance issues for a moment, then the following snippet will do what you need in a single line of code:

BOOL isSubset = [[NSSet setWithArray: array1] isSubsetOfSet: [NSSet setWithArray: mainArray]];
查看更多
Juvenile、少年°
3楼-- · 2020-02-06 03:46

You can use the concept of [NSArray containsObject:], where your objects will be from your array1 like you say "john","smith","alex","loui"

查看更多
成全新的幸福
4楼-- · 2020-02-06 03:48

Run a loop and use isEqualToStiring to verify whether array1 objects exists in mainArray.

查看更多
beautiful°
5楼-- · 2020-02-06 03:55
 NSArray *array1 = [NSArray arrayWithObjects:@"a", @"u", @"b", @"v", @"c", @"f", nil];
    NSMutableArray *mainArray = [NSMutableArray arrayWithObjects:@"a", @"u", @"I", @"G", @"O", @"W",@"Z",@"C",@"T", nil];
    int j=0;
    for(int i=0; i < mainArray.count; i++)
    {
        if (j < array1.count)
        {
            for( j=0; j <= i; j++)
            {
                if([[mainArray objectAtIndex:i] isEqualToString:[array1 objectAtIndex:j]] )
                {
                    NSLog(@"%@",[mainArray objectAtIndex:i]);
                }
            }
        }

    }
查看更多
神经病院院长
6楼-- · 2020-02-06 03:57

If you just need to check if all objects from array1 are in mainArray, you should just use NSSet e.g.

BOOL isSubset = [[NSSet setWithArray:array1] isSubsetOfSet:[NSSet setWithArray:mainArray]] 

if you need to check which objects are in mainArray, you should take a look at NSMutableSet

NSMutableSet *array1Set = [NSMutableSet setWithArray:array1];
[array1Set intersectSet:[NSSet setWithArray:mainArray]];
//Now array1Set contains only objects which are present in mainArray too
查看更多
该账号已被封号
7楼-- · 2020-02-06 03:58

Use NSArray filteredArrayUsingPredicate: method. Its really fast to find out similar types of object in both arrays

NSPredicate *intersectPredicate = [NSPredicate predicateWithFormat:@"SELF IN %@", otherArray];
NSArray *intersectArray = [firstArray filteredArrayUsingPredicate:intersectPredicate];

From above code intersect array gives you same objects which are in other array.

查看更多
登录 后发表回答