当密钥是NSNumber时,我可以调用nsdictionary的valueForKeyPath吗?

时间:2014-08-04 10:32:58

标签: ios objective-c cocoa-touch nsdictionary key-value

我有一个名为" optionsDictionary"的NSDictionary属性。该字典中的一个对象是嵌套字典,它根据答案保存问题的评分数据。该对象的关键是"得分"。

optionsDictionary = 
{
  "score":{
            6747:{
                   "a":"scoring data for answer 'a' to question with ID 6747"
                   "b":"scoring data for answer 'b' to question with ID 6747"
                 }
            3653:{
                   "a":"scoring data for answer 'a' to question with ID 3653"
                   "b":"scoring data for answer 'b' to question with ID 3653"
                 }
          }
}

我试图通过执行以下操作来获取数据:

NSString* scoringData = [self.optionsDictionary valueForKeyPath:[NSString stringWithFormat:@"score.%@.%@",question.qID,question.qAnswer]];

我知道如果所有键都是字符串,这将完美地工作,但问题ID键(6747和3653)是NSNumbers。我仍然可以使用valueForKeyPath,路径中的一个键是NSNumber吗?

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

以下内容如果下标有效,只要下标中使用的类型与每个字典的键匹配:

NSString *scoringData = self.optionsDictionary[question][qID][question.qAnswer];

答案 1 :(得分:1)

为什么使用NSKeyValueCoding协议方法?!?!

最好尝试使用NSDictionary方法:

objectForKey:

尝试将NSDictionary键作为字符串,例如:

NSDictionary* scoringData = self.optionsDictionary[@"score"];

顺便说一句,你的JSON不是一个有效的,你更好的添加,(逗号)每个键值对象(json)和收集2个或更多jsons到array []:

{
  "optionsDictionary" : 
  {
    "score":{
              "6747":[
                     "a":"scoring data for answer 'a' to question with ID 6747",
                     "b":"scoring data for answer 'b' to question with ID 6747"
                  ],
              "3653":[
                     "a":"scoring data for answer 'a' to question with ID 3653",
                     "b":"scoring data for answer 'b' to question with ID 3653"
                   ]
            }
  }
}