昨天遇到一個(gè)需求瓦宜,大致是這樣子的
{
key = value;
anotherKey = anotherValue;
}
將上面的 Dictionary 轉(zhuǎn)換成
{
newKey = value;
newAnotherKey = anotherValue;
}
也就是值不變,key 變化站宗。那就是一個(gè) KeyMapping 映射
那自然是用一個(gè) Category 來做秧骑,參數(shù)是 映射字典
上代碼
@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
然后是簡(jiǎn)單的使用
NSDictionary *oringinDic = @{@"key":@"value",@"anotherKey":@"anotherValue"};//原來的字典
NSDictionary *mappingDic = @{@"key":@"newKey"};//映射字典,這里只映射一個(gè)Key
NSDictionary *newDic = [oringinDic zbRemapKeyWithMappingDictionary:mappingDic removingNullValues:YES];
NSLog(@"映射后的 Dic: %@", newDic);
打印一下
映射前: {
key = value;
anotherKey = anotherValue;
}
映射后: {
newKey = value;
anotherKey = anotherValue;
}