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;
}
Description
Need a method that merges the contents of one dictionary into another recursively. This would be a category of NSDictionary.
Solution