0

我有两个数组,一个保存键值(myKeys),另一个保存 NSString 对象(myStrings)。我想使用两个数组来使用快速枚举填充单个 NSDictionary (myDictionary),但不知道如何?

for (NSNumber *key in myKeys) {

   [self.myDictionary setObject @"here is where the value should go from the 'other' array forKey: key];

}

我将如何在此处考虑 NSArray 对象?

4

3 回答 3

5

检查文档, NSDictionary 无需枚举即可做到这一点。

NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:myObjects forKeys:myKeys];

如果您尝试将值添加到现有的 mutableDictionary,它也可以这样做。

[mutableDictionary addEntriesFromDictionary:dictionary];
于 2014-01-24T17:54:23.610 回答
0

我建议使用常规的 for 循环并只使用索引处的对象,或者只是制作自己的计数器并做同样的事情。但是,如果您想保留 foreach 并且不想制作自己的计数器,则可以这样做:

[self.myDict setObject:[myStrings objectAtIndex:[myKeys indexOfObject:key]] 
                forKey: key];
于 2014-01-24T17:54:03.147 回答
0

如果你真的想加快你的 for 循环,你可以使用 NSEnumerationConcurrent 选项。此枚举选项可确保您使用 iDevice 上的所有可用资源。

[myArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSNumber *key, NSUInteger idx, BOOL *stop) {
    [self.myDictionary setObject @"here is where the value should go from the 'other' array" forKey: key];
}];

有关并发循环的更多信息,请参阅这篇文章: 何时使用 NSEnumerationConcurrent

于 2014-01-24T17:57:46.613 回答