2012-04-19 73 views
0

我打算将iOS SDK中的NSDictionary *对象转换为NSString *。[iOS] [objC]无法将NSDictionary中的值转换为NSString

比方说我的NSDictionary对象还具有以下键值对: {“APS”:{“徽章”:9,“警告”:“你好”}}(注意值本身是一个的NSDictionary对象) 和我希望它转换成带有键值对的哈希映射为{“aps”:“badge:9,alert:hello”}(注意值只是一个字符串)。

我可以使用下面的代码打印在NSDictionary中的值:

NSDictionary *userInfo; //it is passed as an argument and contains the string I mentioned above 
for (id key in userInfo) 
{ 
    NSString* value = [userInfo valueForKey:key]; 
    funct([value UTF9String]; // my function 
} 

,但我没能像打电话值UTT8String对象上任何的NSString方法。它给了我错误“终止应用程序由于未捕获的异常NSInvalidArgumentException:原因[_NSCFDictionary UTF8String]:无法识别的选择器发送到实例

+0

当你尝试时会发生什么? – borrrden 2012-04-19 05:53:38

+0

它使我的错误“终止应用程序由于未捕获的异常NSInvalidArgumentException:原因[_NSCFDictionary UTF8字符串]:发送到实例 – 2012-04-19 05:57:25

+1

无法识别的选择听起来就像是一个嵌套的字典 – danielbeard 2012-04-19 05:57:52

回答

0

我找到了最简单的方法。调用NSDictionary对象的描述方法给了我我需要的东西。愚蠢的错过了第一次去。

1

您将不得不递归处理字典结构,这里是一个例子,你应该能够适应:

-(void)processParsedObject:(id)object{ 
    [self processParsedObject:object depth:0 parent:nil]; 
} 

-(void)processParsedObject:(id)object depth:(int)depth parent:(id)parent{ 

    if([object isKindOfClass:[NSDictionary class]]){ 

     for(NSString * key in [object allKeys]){ 
     id child = [object objectForKey:key]; 
     [self processParsedObject:child depth:depth+1 parent:object]; 
     }       


    }else if([object isKindOfClass:[NSArray class]]){ 

     for(id child in object){ 
     [self processParsedObject:child depth:depth+1 parent:object]; 
     } 

    } 
    else{ 
     //This object is not a container you might be interested in it's value 
     NSLog(@"Node: %@ depth: %d",[object description],depth); 
    } 


} 
+0

似乎也工作! – 2012-04-23 10:43:38

0

您需要在循环应用到每个孩子,而不是主词典你自己说你有一个字典词典:

for(id key in userInfo) 
{ 
    NSDictionary *subDict = [userInfo valueForKey:key]; 
    for(id subKey in subDict) 
    { 
     NSString* value = [subDict valueForKey:subKey]; 
    } 
} 

这个循环假设你拥有整个dicti第一级的onary,否则你需要使用danielbeard的递归方法。

相关问题