4

Is there an easy way for me to pull out a particular value from an NSDictionary, without calling objectForKey for each level I want to go down?

For example:

{
    response = {
        data = {
            foo = "bar";
        };
        user = {
            "first_name" = "Joe";
            "last_name" = "Bloggs";
        };
    };
}

Is there any easy way to pull out first_name? In reality, my data is much more nested than this, and I want to pull out data at various different levels.

Thanks.

Sam Starling
  • 5,298
  • 3
  • 35
  • 52

2 Answers2

5

Key Value Coding is your friend!

Using KVC, you should be able to do something like:

NSString * name = [response valueForKeyPath:@"user.first_name"];

Here's another related question with answers that may help you which also points to another question with further elaboration.

Here is the documentation for valueForKeyPath:.

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
2

Use valueForKeyPath? It's in Apple's docs.

This is for an array, but should work similarly: theocacao.com on NSArray and KVC

Also, make sure you're using strings as the key. You can run into problems.

For reference on Key-Value Coding: Apple Docs on Key-Value Coding

lewiguez
  • 3,813
  • 1
  • 25
  • 40