Friday, June 21, 2013

NSMutableSet intersectSet example in Objective C (iOS).


NSMutableSet intersectSet

Removes from the receiving set each object that isn’t a member of another given set.

- (void)intersectSet:(NSSet *)otherSet

Parameters of [NSMutableSet intersectSet]
otherSet
The set with which to perform the intersection.

NSMutableSet intersectSet example.
Use NSMutableSet:

NSMutableSet *intersection = [NSMutableSet setWithArray:array1];
[intersection intersectSet:[NSSet setWithArray:array2]];
[intersection intersectSet:[NSSet setWithArray:array3]];

NSArray *array4 = [intersection allObjects];

Example of [NSMutableSet intersectSet].
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];

NSMutableSet intersectSet example.
Something like this?

NSMutableSet* set1 = [NSMutableSet setWithArray:array1];
NSMutableSet* set2 = [NSMutableSet setWithArray:array2];
[set1 intersectSet:set2]; //this will give you only the obejcts that are in both sets

NSArray* result = [set1 allObjects];
This has the benefit of not looking up the objects in the array, while looping through another array, which has N^2 complexity and may take a while if the arrays are large.

Edit: set2 doesn't have to be mutable, might as well use just

NSSet* set2 = [NSSet setWithArray:array2];

End of NSMutableSet intersectSet example article.