【问题标题】:[iOS][objC] unable to convert value in NSDictionary to NSString[iOS][objC] 无法将 NSDictionary 中的值转换为 NSString
【发布时间】:2012-04-19 05:51:38
【问题描述】:

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

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

【问题讨论】:

  • 它给了我错误“由于未捕获的异常 NSInvalidArgumentException 导致应用程序终止:原因 [_NSCFDictionary UTF8String]:无法识别的选择器发送到实例
  • 听起来像是嵌套字典
  • 你为什么要从 NSDictionary 转到 HashMap?
  • @danielbeard 是对的……它看起来像是嵌套的。
  • 你可以试试[value UTF8String];

标签: ios nsstring 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);
   }


}

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      我找到了最简单的方法。在 NSDictionary 对象上调用 description 方法给了我我真正需要的东西。第一次就错过了,真是太愚蠢了。

      【讨论】:

        猜你喜欢
        • 2018-01-15
        • 1970-01-01
        • 1970-01-01
        • 2014-04-06
        • 2013-09-15
        • 1970-01-01
        • 2017-04-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多