Search code examples
iosarraysstringcountnsset

NSSet count unique entries compared to 2nd set


I've got two sets and use isSubsetOfSet: to determine if the receiving set is all present in the other set. However, I need to figure out how many unique entries are in the receiving set when isSubsetOfSet: fails. For example:

NSSet *set1 = [NSSet setWithObjects:@"1", @"2", @"3"];
NSSet *set2 = [NSSet setWithObjects:@"1", @"3", @"4", @"5"];

if (![set1 isSubsetOfSet:set2]) {

    How many items are in set1 that are not in set2? The answer should be 1. (a string "2")
}

Any help would be greatly appreciated. Thanks.


Solution

  • You can make a mutable copy of set1, and subtract set2 from it, like this:

    NSMutableSet *missing = [NSMutableSet setWithSet:set1];
    [missing minusSet:set2];
    

    Now missing contains all objects from set1 missing in set2. You can skip the call of isSubsetOfSet:, comparing missing.length to zero instead.