0

我打算将 iOS SDK 中的 NSDictionary* 对象转换为 NSString*。

假设我的 NSDictionary 对象具有以下键值对: {"aps":{"badge":9, "alert":"hello"}} (注意值本身是一个 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]:无法识别的选择器已发送到实例

4

3 回答 3

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);
   }


}
于 2012-04-19T06:17:25.347 回答
0

您需要将该循环应用于每个孩子,而不是主字典。您说自己在字典中有字典:

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

此循环假定您在第一级拥有整个字典,否则您将需要使用 danielbeard 的递归方法。

于 2012-04-19T09:15:36.117 回答
0

我找到了最简单的出路。在 NSDictionary 对象上调用 description 方法给了我我真正需要的东西。愚蠢地在第一次去时错过了它。

于 2012-04-20T07:05:23.240 回答