包含一个NSArray的NSDictionary [英] NSDictionary containing an NSArray

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

问题描述

我很新的Objective-C和还没有很多经验用C所以请原谅我的无知。我的问题是,是否有可能到数组添加到字典?以下是我在Python做的,这是非常方便的:

I am very new to Objective-C and haven't had a lot of experience with C so please excuse my ignorance. My question is this, is it possible to add an Array to a Dictionary? Here is what I'd do in Python, and it's very convenient:

if 'mykey' not in mydictionary:
    mydictionary['mykey']=[] # init an empty list for 'mykey'
mydictionary['mykey'].append('someitem')

我想是这样的,即作品:

I want something like this, that works:

NSMutableDictionary *matchDict = [NSMutableDictionary dictionary];
NSMutableArray *matchArray = [NSMutableArray array]; 

while (blah):
    [matchDict setObject: [matchArray addObject: myItem] forKey: myKey];

我到处,没有运气,刚想放弃。任何反馈将AP preciated!

I looked everywhere with no luck, just about to give up. Any feedback will be appreciated!

推荐答案

这是一个从你在Python做了什么,没有真正的不同。

It's not really different from what you did in python.

NSMutableDictionary *matchDict = ...
NSMutableArray *matchArray = ...
[matchDict setObject:matchArray forKey:someKey];
// This is same as: mydictionary['mykey']=[]


// 'matchArray' is still a valid pointer so..
[matchArray addObject:someObj];

// or later if 'matchArray' were no longer in scope 
// it would look like this:

NSMutableArray* arrayForKey = [matchDict objectForKey:someKey];
[arrayForKey addObject:someObj];

// or more simply:
[[matchDict objectForKey:someKey] addObject:someObj];

// this is same as: mydictionary['mykey'].append('someitem')

修改

所以,如果你需要添加阵列为多个键,你可以这样做:

So if you need to add arrays for more than one key you might do this:

由于两个键的数组:

NSArray *keys = [NSArray arrayWithObjects:@"key0",@"key1", nil];

和一本字典...

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:[keys count]];

下面是你如何可以为每个键的数组:

Here is how you could create an array for each key:

for (id key in keys) {

    // Create a new array each time...

    NSMutableArray *array = [NSMutableArray array];

    // and insert into dictionary as value for this key

    [dict setObject:array forKey:key];
}

希望,让你的想法。

Hopefully that gives you the idea.

这篇关于包含一个NSArray的NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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