How to store an NSArray in an NSDictionary?

独自空忆成欢 提交于 2019-12-23 10:14:19

问题


I'm trying to teach myself but am struggling with how to store something like an NSArray inside an NSDictionary.

Let's say hypothetically you had a NSDictionary for recipes:

Let's say the NSDictionary had keys like:

Spaghetti, Fettucine Alfredo, Grilled Chicken Salad

And the NSDictionary had an NSArray which was simply a list of ingredients.

I suppose the equivalent PHP code would be something like:

$['Spaghetti'] = array('Spaghetti Pasta', 'Spaghetti Sauce', 'Meatballs');
$['Fettucine Alfredo'] = array('Fettucine Pasta', 'Alfredo Sauce');
$['Grilled Chicken Salad'] = array('Lettuce', 'Grilled Chicken', 'Croutons');

I'm struggling with how I can add an NSArray to the NSDictionary. Then what if I wanted to remove an element or add an element to the array? How is it retrieved and deleted or added to?


回答1:


NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
  [NSArray arrayWithObjects:@"Spaghetti Pasta", @"Tomato Sauce", nil], @"Spaghetti",
  [NSArray arrayWithObjects:@"Fettuccine Pasta", @"Alfredo Sauce", nil], @"Fettuccine Alfredo",
  [NSArray arrayWithObjects:@"Lettuce", @"Grilled Chicken", @"Croutons", nil], @"Grilled Chicken Salad",
  nil];

You can add any object type to a dictionary as a value. For more on dictionaries, see the documentation.



来源:https://stackoverflow.com/questions/3155328/how-to-store-an-nsarray-in-an-nsdictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!