Search code examples
objective-cnsdictionaryxcode8nsmutabledictionary

Add values of different NSMutableDictionaries with same Keys


I am on Xcode 8.2, OSX not iOS, Objective-C

I have several different NSMutableDictionaries like:

NSMutableDictionary* dict1 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                             [NSNumber numberWithInt:1],@"key1",
                             [NSNumber numberWithInt:14],@"key2",
                             nil];

NSMutableDictionary* dict2 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                             [NSNumber numberWithInt:9],@"key1",
                             [NSNumber numberWithInt:1],@"key2",
                             [NSNumber numberWithInt:99],@"key3",
                             nil];

// and many more

I need to combine them in a way that the values for a matching key are added so we get a new NSMutableDictionary (or unmutable for the result) like this for the above example:

NSMutableDictionary* result = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                             [NSNumber numberWithInt:10],@"key1", // 9+1
                             [NSNumber numberWithInt:15],@"key2", // 14+1
                             [NSNumber numberWithInt:99],@"key3", // stays the same
                             nil];

Solution

  • Here you go:

    NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
    for (NSDictionary *dictionary in @[dict1, dict2]) {
        // enumerate the keys and objects in the dictionary
        [dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSNumber *dictionaryNumber, BOOL *stop){
            // check if the key exists in result
            NSNumber *resultNumber = result[key];
            if (resultNumber)
                // the key exists in result, add the number to the existing number
                result[key] = [NSNumber numberWithInteger:resultNumber.integerValue + dictionaryNumber.integerValue];
            else
                // the key didn't exist in result, add the key and the number to result
                result[key] = dictionaryNumber;
        }];
    }