NSArray - check if objects are in an array?

10,724

Solution 1

Are you sure that you need NSArrays? For intersections it would be better to use NSSets. For more information about the usage of NSArrays and NSSet please refer to Cocoa with Love: NSArray or NSSet, NSDictionary or NSMapTable.

If you are using NSSet you have to create a new NSMutableSet, which has the method intersectSet:, which can be used for your purpose:

NSMutableSet *set1 = [[NSMutableSet alloc] initWithObjects:@"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", nil];
NSMutableSet *set2 = [[NSMutableSet alloc] initWithObjects:@"2", @"4", @"6", @"8", @"10", @"12", @"14", @"18", nil];

NSLog(@"set1: %@", set1);
NSLog(@"set2: %@", set2);
[set1 intersectSet:set2];
NSLog(@"isec: %@", set1);

You can create a NSMutableSet from an NSArray using the addObjectsFromArray: method:

NSArray *array = [[NSArray alloc] initWithObjects:@"1", @"2", nil];
NSMutableSet *set = [[NSMutableSet alloc] init];
[set addObjectsFromArray:array];

It may be that you can also filter the NSArray using the filterUsingPredicate: method, however I have never worked with NSPredicates therefore this is only an assumption.

Solution 2

The easiest (but not necessarily fastest (?)) way would be something like

NSMutableSet *intersection = [NSMutableSet setWithArray:smallArray];
[intersection intersectSet:[NSSet setWithArray:bigArray];
NSArray *result = [NSArray arrayWithSet:intersection];

You'll have to sort the resulting array again, however.

Share:
10,724
Zac Altman
Author by

Zac Altman

Updated on June 04, 2022

Comments

  • Zac Altman
    Zac Altman almost 2 years

    I have 2 arrays. One is a large static group of 600 objects, the other is a small varying group of 10 objects.

    I want to take any common objects between the two groups and put them in a new array.

    So lets say the large group contains 600 objects named 1 to 600. The smaller group contains 9 objects: 1, 2, 3, 4, 5, 6, a, b, c. I want to be able to create a new array that contains the objects 1, 2, 3, 4, 5, 6.

    What is the best way to do this?

  • TechZen
    TechZen about 14 years
    This is a good suggestion with the caveat that for an NSSet, every object in each set must be unique. If your arrays have duplicate values e.g. [0,1,2,3,2,4], NSSet will not work.
  • Zac Altman
    Zac Altman about 14 years
    On the contrary, NSSet is quite useful because it doesn't add duplicates (when you add an array to it). Thanks for the help ComSubVie and MrMage. Its all working now.
  • TechZen
    TechZen about 14 years
    It depends on your problem space. If you want to record how many duplicates exist, even if they are duplicates of the same object/item, then NSSet will not work.
  • MrMage
    MrMage about 14 years
    Otherwise you can still use NSCountedSet.