Neo
Neo

Reputation: 167

Objective C NSMutableDictionary

I have a question about NSMutableDictionary,

Let's say I have two set of NSMutableDictionary:

NSMutableDictionary *oddNumber
NSMutableDictionary *randomNumber

Is there a function to check value of randomNumber is SUBSET of value of oddNumber or not?

Upvotes: 0

Views: 131

Answers (4)

Willeke
Willeke

Reputation: 15589

Short:

BOOL isSubset = [[oddNumber dictionaryWithValuesForKeys:[randomNumber allKeys]] isEqualToDictionary:randomNumber]

or faster:

__block BOOL isSubset = YES;
[randomNumber enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
    id value = [oddNumber objectForKey:key];
    if (!value || ![value isEqual:obj]) {
        isSubset = NO;
        *stop = YES;
    }
}];

Upvotes: 0

gnasher729
gnasher729

Reputation: 52538

Look at the values that you have. Make sure they have an isEqual: method and a hash method, so you can add them to a set. Create an NSSet with all values of the second dictionary, then iterate through the first dictionary and check which values are in the set.

Note that creating a set with N values takes O (N) time if the values have a decent hash function, and looking up a value in a set is constant time.

Upvotes: 0

Ronak Chaniyara
Ronak Chaniyara

Reputation: 5435

You can do something like this,

    NSMutableDictionary *oddNumber;
    NSMutableDictionary *randomNumber;
    // Create arrays
    NSArray *arroddNumber = [oddNumber allValues];
    NSArray *arrrandomNumber = [oddNumber allValues];


    // Turn the arrays into sets and intersect the two sets
    NSMutableSet *oddNumberSet = [NSMutableSet setWithArray:arroddNumber];
    NSMutableSet *randomNumbersSet = [NSMutableSet setWithArray:arrrandomNumber];

    [oddNumberSet intersectSet:randomNumbersSet];

    // The Values present in both arrays
    NSLog(@"Common Values : %@", oddNumberSet);

Upvotes: 1

Abizern
Abizern

Reputation: 150605

You could get the values for each dictionary using the values method. This returns an array. You could then convert these arrays to sets, which have methods to check if one set is a subset of another.

Upvotes: 0

Related Questions