Search code examples
objective-ccocoansarray

How do I traverse a multi dimensional NSArray?


I have array made from JSON response.

NSLog(@"%@", arrayFromString) gives the following:

{ meta = { code = 200; }; response = { groups = ( { items = ( { categories = ( { icon = "http://foursquare.com/img/categories/parks_outdoors/default.png"; id = 4bf58dd8d48988d163941735;

and so on...

This code

NSArray *arr = [NSArray arrayWithObject:[arrayFromString valueForKeyPath:@"response.groups.items"]];

gives array with just one element that I cannot iterate through. But if I write it out using NSLog I can see all elements of it.

At the end I would like to have an array of items that I can iterate through to build a datasource for table view for my iPhone app.

How would I accomplish this?

EDIT:

I have resolved my issue by getting values from the nested array (objectAtIndex:0):

for(NSDictionary *ar in [[arrayFromString valueForKeyPath:@"response.groups.items"] objectAtIndex:0]) {
        NSLog(@"Array: %@", [ar objectForKey:@"name"]);
    }

Solution

  • First, the data structure you get back from the JSON parser is not an array but a dictionary: { key = value; ... } (curly braces).

    Second, if you want to access a nested structure like the items, you need to use NSObject's valueForKeyPath: method. This will return an array of all items in your data structure:

    NSLog(@"items: %@", [arrayFromString valueForKeyPath:@"response.groups.items"]);
    

    Note that you will loose the notion of groups when retrieving the item objects like this.