NSDictionary包含NSArray

时间:2011-04-03 01:20:13

标签: objective-c arrays data-structures dictionary

我对Objective-C很新,并且没有很多C经验,所以请原谅我的无知。我的问题是,是否可以在字典中添加数组?这是我在Python中所做的,而且非常方便:

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

我想要这样的东西,有效:

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

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

我到处都没有运气,只是放弃了。任何反馈将不胜感激!

3 个答案:

答案 0 :(得分:5)

这与你在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')

修改

因此,如果您需要为多个密钥添加数组,则可以执行此操作:

给出一组两个键:

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

还有一本字典......

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

以下是为每个键创建数组的方法:

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];
}

希望能给你这个想法。

答案 1 :(得分:1)

以下是如何操作:

    [matchDict setObject:matchArray forKey:@"myKey"];

3个月前我不得不问自己this question,所以不要过于担心要求;)

答案 2 :(得分:0)

在考虑之后我最终解决了问题。如果要动态填充每个键的数组,可以这样执行:

While (something)
{
    // check if key is already in dict.
    if ([_matchesDictionary objectForKey: hashKey]) 
        {
            // pull existing array from dict and add new entry to array for said key.
            NSMutableArray *keyArray = [_matchesDictionary objectForKey: hashKey];
            [keyArray addObject: newPath];

            // put the array back into the dict for said key.
            [_matchesDictionary setObject: keyArray forKey: hashKey];

     } else {

            // create new array, assign empty array to said key in dict.
            NSMutableArray *keyArray = [NSMutableArray array];
            [keyArray addObject: newPath];
            [_matchesDictionary setObject: keyArray forKey: hashKey];

     } 

}

这会产生{(' value1',value2'等......):' somekey'}

感谢@Antal和@Firoze的所有帮助,你帮助我解决了问题。只需要停止思考" Python"。如果你们中的任何一个看到任何问题或更好的实现让我知道。