Snips
Snips

Reputation: 6763

Extracting a key/value pair from an NSDictionary

Is there a convenient way to obtain both a key/value pair from an NSDictionary?

Say I have a NSDictionary, partyGuest,

{
   name = "jim";
   age = 28;
   occupation = "astronaut";
   favouriteMeal = 
      {
         starter = "fish head soup";
         mainCourse = "roast armadillo";
         dessert = "sugar plum fairy cakes";
      }
}

I'd like to get obtain a key/value pair within that, like so,

NSDictionary *guestFoodChoice = [partyGuest itemForKey:@"favouriteMeal"];

...and have that obtain both the key and the value,

   guestFoodChoice =
{
   favouriteMeal = 
      {
         starter = "fish head soup";
         mainCourse = "roast armadillo";
         dessert = "sugar plum fairy cakes";
      }
}

It seems there should be, but as I can't see an obvious method, maybe I'm missing something?

Upvotes: 1

Views: 3967

Answers (3)

Chuck
Chuck

Reputation: 237060

It sounds like you basically want to get a dictionary with some subset (maybe just one) of key-value pairs in another dictionary. If that's right, the Key-Value Coding method dictionaryWithValuesForKeys: is what you want.

NSDictionary *guestFoodChoice = [partyGuest dictionaryWithValuesForKeys:[NSArray arrayWithObject:@"favouriteMeal"]];

Upvotes: 5

bbum
bbum

Reputation: 162712

See enumerateKeysAndObjectsUsingBlock:.

Upvotes: 2

Paul Tiarks
Paul Tiarks

Reputation: 1921

NSDictionary *guestFoodChoice = [NSDictionary dictionaryWithObjectsAndKeys:[partyGuest itemForKey:@"favouriteMeal"],@"favouriteMeal",nil];

Upvotes: 1

Related Questions