0

I have an NSDictionary property called "optionsDictionary". One of the objects in that dictionary is nested dictionaries that hold scoring data for questions based on their answers. The key for that object is "score".

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"
                 }
          }
}

I am trying to get scoring data by doing something like:

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

I know this will work perfectly if all keys were strings, but the question ID keys (6747 and 3653) are NSNumbers. Can I still use valueForKeyPath with one of the keys along the path being an NSNumber?

Thanks for your help!

Ahmed Hamed
  • 504
  • 1
  • 3
  • 11

2 Answers2

1

What about the following, which will work as long as the types used in the subscripting matches the keys of each dictionary:

NSString *scoringData = self.optionsDictionary[question][qID][question.qAnswer];
Droppy
  • 9,691
  • 1
  • 20
  • 27
1

Why r u using the NSKeyValueCoding protocol method?!?!

U better try using NSDictionary method:

objectForKey:

Try to get NSDictionary key as a string, like:

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

By the way, your JSON is NOT a valid, u better add , (comma) between each key-value object (json) and gather 2 or more jsons into 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"
                   ]
            }
  }
}
gran33
  • 12,421
  • 9
  • 48
  • 76