Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep combine NSDictionaries

I need to merge two NSDictionarys into one provided that if there are dictionaries within the dictionaries, they are also merged.

More or less like jQuery's extend function.

like image 295
Alexsander Akers Avatar asked Oct 25 '10 03:10

Alexsander Akers


People also ask

How do you merge dictionaries in a dictionary?

For anyone with lists as the final nested level under the dicts, you can do this instead of raising the error to concatenate the two lists: a[key] = a[key] + b[key] . Thanks for the helpful answer. > if you want to keep a you could call it like merge(dict(a), b) Note that nested dicts will still be mutated.

Can we merge two dictionaries?

In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.

Can dictionaries be nested to any depth?

Dictionaries can be nested to any depth. Dictionaries are mutable. All the keys in a dictionary must be of the same type.


1 Answers

NSDictionary+Merge.h

#import <Foundation/Foundation.h>

@interface NSDictionary (Merge)

+ (NSDictionary *) dictionaryByMerging: (NSDictionary *) dict1 with: (NSDictionary *) dict2;
- (NSDictionary *) dictionaryByMergingWith: (NSDictionary *) dict;

@end

NSDictionary+Merge.m

#import "NSDictionary+Merge.h"

@implementation NSDictionary (Merge)

+ (NSDictionary *) dictionaryByMerging: (NSDictionary *) dict1 with: (NSDictionary *) dict2 {
    NSMutableDictionary * result = [NSMutableDictionary dictionaryWithDictionary:dict1];

[dict2 enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
    if (![dict1 objectForKey:key]) {
        if ([obj isKindOfClass:[NSDictionary class]]) {
            NSDictionary * newVal = [[dict1 objectForKey: key] dictionaryByMergingWith: (NSDictionary *) obj];
            [result setObject: newVal forKey: key];
        } else {
            [result setObject: obj forKey: key];
        }
    }
}];

    return (NSDictionary *) [[result mutableCopy] autorelease];
}
- (NSDictionary *) dictionaryByMergingWith: (NSDictionary *) dict {
    return [[self class] dictionaryByMerging: self with: dict];
}

@end
like image 120
Alexsander Akers Avatar answered Oct 07 '22 20:10

Alexsander Akers