hivesolutions / cameo

A generic framework for iOS interaction
http://cameo.hive.pt
Apache License 2.0
0 stars 0 forks source link

Category support for merging two dictionaries #9

Closed tsilva closed 9 years ago

tsilva commented 9 years ago

Description

Need a method that merges the contents of one dictionary into another recursively. This would be a category of NSDictionary.

Solution

- (NSMutableDictionary *)mergedWithDictionary:(NSDictionary *)dictionary1 {
    // creates a mutable copy of the dictionary
    // into which the contents are going to be merged
    // (otherwise the dictionary may not be editable)
    NSMutableDictionary *dictionary2 = self.mutableCopy;

    // merges each entry of the dictionary
    for(NSString *key in dictionary1) {
        // retrieves the values from both
        // dictionaries for the current key
        id value1 = dictionary1[key];
        id value2 = dictionary2[key];

        // in case both dictionary values are dictionaries
        // then calls this method recursively to merge them
        BOOL isValue1Dict = [value1 isKindOfClass:NSDictionary.class];
        BOOL isValue2Dict = value2 != nil && [value2 isKindOfClass:NSDictionary.class];
        if(isValue1Dict && isValue2Dict) {
            dictionary2[key] = [value2 mergeDictionary:value1];
        }
        // otherwise assigns the first dictionary's
        // value into the second dictionary
        else {
            dictionary2[key] = value1;
        }
    }

    // returns the merged dictionary
    return dictionary2;
}
joamag commented 9 years ago

This is now considered close with result = [first merged:second]