如何在 NSDictionary 中存储 NSArray? [英] How to store an NSArray in an NSDictionary?

查看:57
本文介绍了如何在 NSDictionary 中存储 NSArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自学,但正在努力解决如何在 NSDictionary 中存储类似 NSArray 之类的内容.

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

假设您有一个 NSDictionary 的食谱:

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

假设 NSDictionary 有如下键:

Let's say the NSDictionary had keys like:

意大利面,意大利细面条阿尔弗雷多,烤鸡肉沙拉

Spaghetti, Fettucine Alfredo, Grilled Chicken Salad

NSDictionary 有一个 NSArray,它只是一个成分列表.

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

我想等效的 PHP 代码将类似于:

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');

我正在为如何将 NSArray 添加到 NSDictionary 而苦苦挣扎.那么如果我想删除一个元素或向数组中添加一个元素呢?如何检索、删除或添加?

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?

推荐答案

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.

这篇关于如何在 NSDictionary 中存储 NSArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆