昨天遇到一个需求,大致是这样子的
{
key = value;
anotherKey = anotherValue;
}
将上面的 Dictionary 转换成
{
newKey = value;
newAnotherKey = anotherValue;
}
也就是值不变,key 变化。那就是一个 KeyMapping 映射
那自然是用一个 Category 来做,参数是 映射字典
上代码
@interface NSDictionary (ZBKeyMapping)
- (NSDictionary *)zbRemapKeyWithMappingDictionary:(NSDictionary *)keyMappingDic removingNullValues:(BOOL)removeNulls;
@end
@implementation NSDictionary (ZBKeyMapping)
- (NSDictionary *)zbRemapKeyWithMappingDictionary:(NSDictionary *)keyMappingDic removingNullValues:(BOOL)removeNulls {
__block NSMutableDictionary *newDictionary = [NSMutableDictionary dictionaryWithCapacity:[self count]];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if (removeNulls) {
if ([obj isEqual:[NSNull null]]) {
return;
}
}
id newKey = keyMappingDic[key];
if (!newKey) {
[newDictionary setObject:obj forKey:key];
} else {
[newDictionary setObject:obj forKey:newKey];
}
}];
return [newDictionary copy];
}
@end
然后是简单的使用
NSDictionary *oringinDic = @{@"key":@"value",@"anotherKey":@"anotherValue"};//原来的字典
NSDictionary *mappingDic = @{@"key":@"newKey"};//映射字典,这里只映射一个Key
NSDictionary *newDic = [oringinDic zbRemapKeyWithMappingDictionary:mappingDic removingNullValues:YES];
NSLog(@"映射后的 Dic: %@", newDic);
打印一下
映射前: {
key = value;
anotherKey = anotherValue;
}
映射后: {
newKey = value;
anotherKey = anotherValue;
}