lettsss
lettsss

Reputation: 7

Is there a method to check if 2 NSDictionaries contain the same keys?

So something like

- (BOOL)isSameValues:(NSArray*)array1 and:(NSArray*)array2
{
    NSCountedSet *set1 = [NSCountedSet setWithArray:array1];
    NSCountedSet *set2 = [NSCountedSet setWithArray:array2];
    return [set1 isEqualToSet:set2];
}

But with NSDictionaries. The above returns YES if the two arrays have the same values. I need to see if the keys of 2 dictionaries are the same, ignoring the values. Duplicates can be ignored for my purposes.

Upvotes: 0

Views: 395

Answers (1)

gruntledcustomer
gruntledcustomer

Reputation: 253

You can use your function, but replace NSCountedSet by NSSet (this isn't too important as dictionaries can't have duplicate keys), and use the allKeys property of NSDictionary. So:

- (BOOL)haveSameKeys:(NSDictionary *)dictionary1 and:(NSDictionary *)dictionary2
{
    NSSet *set1 = [NSSet setWithArray:[dictionary1 allKeys]];
    NSSet *set2 = [NSSet setWithArray:[dictionary2 allKeys]];
    return [set1 isEqualToSet:set2];
}

Upvotes: 2

Related Questions