2021-11-21 08:16:16 +00:00
|
|
|
#import "NSDictionary+Merge.h"
|
|
|
|
|
|
|
|
@implementation NSDictionary (Merge)
|
|
|
|
|
2022-02-07 05:49:27 +00:00
|
|
|
+ (NSDictionary *)dictionaryByMerging:(NSDictionary *)dict1 with:(NSDictionary *)dict2 {
|
|
|
|
NSMutableDictionary *result = [dict1 mutableCopy];
|
2021-11-21 08:16:16 +00:00
|
|
|
|
2022-02-07 05:49:27 +00:00
|
|
|
[dict2 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
|
|
|
|
if(![dict1 objectForKey:key]) {
|
|
|
|
[result setObject:obj forKey:key];
|
|
|
|
} else if([obj isKindOfClass:[NSDictionary class]]) {
|
|
|
|
NSDictionary *newVal = [[dict1 objectForKey:key] dictionaryByMergingWith:(NSDictionary *)obj];
|
|
|
|
[result setObject:newVal forKey:key];
|
2022-02-15 03:55:20 +00:00
|
|
|
} else {
|
|
|
|
BOOL isEmpty = NO;
|
|
|
|
id objTarget = [dict1 objectForKey:key];
|
|
|
|
if([objTarget isKindOfClass:[NSString class]]) {
|
|
|
|
NSString *val = (NSString *)objTarget;
|
|
|
|
isEmpty = [val length] == 0;
|
|
|
|
} else if([objTarget isKindOfClass:[NSNumber class]]) {
|
|
|
|
NSNumber *val = (NSNumber *)objTarget;
|
|
|
|
isEmpty = [val isEqualTo:@(0)];
|
2022-02-17 11:00:35 +00:00
|
|
|
} else if([objTarget isKindOfClass:[NSData class]]) {
|
|
|
|
NSData *val = (NSData *)objTarget;
|
|
|
|
isEmpty = [val length] == 0;
|
2022-02-15 03:55:20 +00:00
|
|
|
}
|
|
|
|
if(isEmpty) {
|
|
|
|
[result setObject:obj forKey:key];
|
|
|
|
}
|
2022-02-07 05:49:27 +00:00
|
|
|
}
|
|
|
|
}];
|
2021-11-21 08:16:16 +00:00
|
|
|
|
2022-02-07 05:49:27 +00:00
|
|
|
return (NSDictionary *)[NSDictionary dictionaryWithDictionary:result];
|
2021-11-21 08:16:16 +00:00
|
|
|
}
|
|
|
|
|
2022-02-07 05:49:27 +00:00
|
|
|
- (NSDictionary *)dictionaryByMergingWith:(NSDictionary *)dict {
|
|
|
|
return [[self class] dictionaryByMerging:self with:dict];
|
2021-11-21 08:16:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@end
|