Adam G
Adam G

Reputation: 1188

Getting values from key in NSDictionary

I'm using the Edmunds API to return a JSON string of vehicle makes for a certain year.

The resulting NSDictionary looks like this:

 makes =     (
                {
            id = 200002038;
            models =   (
                { // not relevant
                }
            );
            name = Acura;
            niceName = acura;
        },
                {
            id = 200001769;
            models =             (
                { // not relevant
                }
            );
            name = "Aston Martin";
            niceName = "aston-martin";
        },

There are a lot more values in this dictionary...how can I loop through through the dictionary to retrieve each of the 'name' values?

Upvotes: 0

Views: 64

Answers (2)

Alex Reynolds
Alex Reynolds

Reputation: 6352

I like valueForKeyPath because you can do so much with it and it's a one line solution. Tested this and it works in my dev setup. If you know your data is in a predictable format, then you can do amazing things with valueForKeyPath.

NSArray *makeNames = [makes valueForKeyPath:@"name"];

Great info on valueForKeyPath http://nshipster.com/kvc-collection-operators/

Upvotes: 2

David Wong
David Wong

Reputation: 10294

NSMutableArray *makeNames = [NSMutableArray new];
for (NSDictionary *make in makes) {
  NSLog(@"Make name: %@", make[@"name"]);
  [makeNames addObject:make];
}
NSLog(@"Makes array: %@", makeNames);

Upvotes: 0

Related Questions