将字典的所有值更改为字符串

时间:2017-03-16 14:19:08

标签: ios objective-c casting nsdictionary nsmutabledictionary

我想将Dictionary的所有值更改为String,如何处理它?<​​/ p>

如:

{   @"a":"a", 
    @"b":2, 
    @"c":{
      @"c1":3,
      @"c2":4
    }
}

我想转换为:

{   @"a":"a", 
    @"b":"2", 
    @"c":{
      @"c1":"3",
      @"c2":"4"
    }
}

怎么办呢?我想全天。

如果我使用以下方法遍历字典值:

NSArray *valueList = [dictionary allValues];

for (NSString * value in valueList) {
    // change the value to String
}

如果值是字典,那该怎么办?

那么,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

您可以为字典创建类别,并添加类似stringValueForKey:的方法。 实现可以是这样的:

- (NSString)stringValueForKey:(NSString*)key
{
   id value = self[key];
   if( [value respondsToSelector:@selector(stringValue)])
       return [value performSelector:@selector(stringValue)]
   return nil;
}

答案 1 :(得分:0)

您可以使用递归方法执行此操作,它会将所有NSNumber值更改为NSString,并为嵌套字典调用自身。由于字典在枚举时无法变异,因此会创建并填充新字典:

- (void)changeValuesOf:(NSDictionary *)dictionary result:(NSMutableDictionary *)result
{
    for (NSString *key in dictionary) {
        id value = dictionary[key];
        if ([value isKindOfClass: [NSDictionary class]]) {
            NSMutableDictionary * subDict = [NSMutableDictionary dictionary];
            result[key] = subDict;
            [self changeValuesOf:value result:subDict];
        } else if ([value isKindOfClass: [NSNumber class]]) {
            result[key] = [NSString stringWithFormat:@"%@", value];
        } else {
            result[key] = value;
        }
    }
}

NSDictionary *dictionary = @{@"a": @"a", @ "b":@2, @"c": @{@"c1": @3,  @"c2":@4 }};
NSMutableDictionary *result = [NSMutableDictionary dictionary];
[self changeValuesOf:dictionary result:result];
NSLog(@"%@", result);