-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBCMergeDictionary.m
65 lines (45 loc) · 2 KB
/
BCMergeDictionary.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//
// BCMergeDictionary.m
// Bartender
//
// Created by Tom Houpt on 11/20/19.
//
#import "BCMergeDictionary.h"
@implementation NSMutableDictionary (MergeExtensions)
/** mergeWithSourceDictionary
self is target, given dictionary is source
given a source dictionary, merge this dictionary with the source:
if key is in source but not self, add key-object to self
if key is in self and also in source, keep self (ie. replace source with target)
(recurse through subdictionaries so only leaves are replaced)
*/
-(void)mergeWithSourceDictionary:(NSDictionary *)sourceDictionary; {
// don't try to merge a nil dictionary
if (nil == sourceDictionary) { return; }
for (NSString *key in sourceDictionary) {
id value = self[key];
if ([key isEqualToString:@"Body Weight"]) {
NSLog(@"body weight %@", key);
}
// is key not in targetDictionary? then add key-object to targetDictionary
if (nil == value) {
self[key] = sourceDictionary[key];
NSLog(@"added value from source to target at key %@", key);
}
else { // key is in sourceDictionary and targetDictionary
// is key-object a dictionary? then we need to recurse and only add/overwrite leaves
if ([value isKindOfClass:[NSDictionary class]]) {
NSDictionary *sourceSubDictionary = sourceDictionary[key];
// convert sub-dictionary to a mutable dictionary
NSMutableDictionary *targetSubDictionary = [(NSDictionary *)self[key] mutableCopy];
[targetSubDictionary mergeWithSourceDictionary:sourceSubDictionary];
self[key] = targetSubDictionary;
}
else {
// if key-object is not a dictionary, then use target value instead of source (ie don't change target)
// NSLog(@"updated value in target overrides source at key %@", key);
}
}
} // next source key
}
@end