简体   繁体   中英

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?

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"]];
NSDictionary *guestFoodChoice = [NSDictionary dictionaryWithObjectsAndKeys:[partyGuest itemForKey:@"favouriteMeal"],@"favouriteMeal",nil];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM