从NSDictionary中提取键/值对

时间:2011-06-19 15:17:24

标签: iphone objective-c ios

是否有方便的方法从NSDictionary获取键/值对?

说我有一个NSDictionary,partyGuest,

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

我希望获得一个键/值对,就像这样,

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

...并获得密钥和值,

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

似乎应该有,但由于我看不到一个明显的方法,也许我错过了什么?

3 个答案:

答案 0 :(得分:5)

听起来你基本上想要在另一个字典中获得一个包含一些子集(可能只有一个)键值对的字典。如果这是正确的,键值编码方法dictionaryWithValuesForKeys:就是你想要的。

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

答案 1 :(得分:2)

答案 2 :(得分:1)

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