我有两个数组,一个保存键值(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对象?
查看文档,NSDictionary可以在不进行枚举的情况下执行此操作。
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:myObjects forKeys:myKeys];
如果您尝试向现有的mutableDictionary添加值,它也可以这样做。
[mutableDictionary addEntriesFromDictionary:dictionary];
我建议使用常规for循环,而只是在索引处使用object,或者只是创建自己的计数器并执行相同的操作。但是如果你想保留foreach并且不想制作自己的计数器,你可以这样做:
[self.myDict setObject:[myStrings objectAtIndex:[myKeys indexOfObject:key]]
forKey: key];
如果你真的想加速你的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];
}];
有关并发循环的更多信息,请参阅这篇文章:When to use NSEnumerationConcurrent