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"]];
See enumerateKeysAndObjectsUsingBlock:
.
NSDictionary *guestFoodChoice = [NSDictionary dictionaryWithObjectsAndKeys:[partyGuest itemForKey:@"favouriteMeal"],@"favouriteMeal",nil];
精彩评论