Alex Tau
Alex Tau

Reputation: 2639

JSON and nested NSDictionary

After parsing a JSON response, I get an NSDictionary containing other dictionaries which are the values for some keys not known in advance (308, 1):

{
"308":{
    "id":"308",
    .....

},
"1":{
    "id":"1",
    .....
     }
}

How do I use here valueForKey since I dont' know the keys? How to acces the nested dictionaries? Thanks!

Upvotes: 1

Views: 2417

Answers (2)

Oleg Trakhman
Oleg Trakhman

Reputation: 2082

NSDictionary *myDict;
...

NSArray *keys = [myDict allKeys]; //NSArray of dictionary's keys

for (id key in keys) //'foreach' loop for all keys
{
   id aValue = [myDict objectForKey: key]; //getting object from the dictionary
   if([aValue isKindOfClass:[NSDictionary class]])
   {
       //Object is a nested dictionary
       ...
   }
}

Upvotes: 5

djromero
djromero

Reputation: 19641

There are several way to iterate over an NSDictionary. One of them:

NSEnumerator *enumerator = [myDictionary objectEnumerator];
id value;

while ((value = [enumerator nextObject])) {
    /* do something with value */
}

Look "Enumerating Dictionaries" section in NSDictionary Class Reference for more alternatives.

Upvotes: 1

Related Questions