Deep combine NSDictionaries

2019-01-14 03:15发布

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.

7条回答
Animai°情兽
2楼-- · 2019-01-14 03:56

I think this is what you're looking for:

First, you need to make a deep mutable copy, so you can create a category on NSDictionary to do this:

@implementation NSDictionary (DeepCopy)

- (id)deepMutableCopy
{
    id copy(id obj) {
        id temp = [obj mutableCopy];
        if ([temp isKindOfClass:[NSArray class]]) {
            for (int i = 0 ; i < [temp count]; i++) {
               id copied = [copy([temp objectAtIndex:i]) autorelease];
               [temp replaceObjectAtIndex:i withObject:copied];
            }
        } else if ([temp isKindOfClass:[NSDictionary class]]) {
            NSEnumerator *enumerator = [temp keyEnumerator];
            NSString *nextKey;
            while (nextKey = [enumerator nextObject])
                [temp setObject:[copy([temp objectForKey:nextKey]) autorelease]
                         forKey:nextKey];
        } 
        return temp;
    }

    return (copy(self));
}

@end

Then, you can call deepMutableCopy like this:

NSMutableDictionary *someDictionary = [someDict deepMutableCopy];
[someDictionary addEntriesFromDictionary:otherDictionary];
查看更多
登录 后发表回答