如何使用Objective-C中的两个NSArray快速枚举来填充NSDictionary?

问题描述 投票:0回答:3

我有两个数组,一个保存键值(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对象?

objective-c for-loop nsdictionary fast-enumeration
3个回答
5
投票

查看文档,NSDictionary可以在不进行枚举的情况下执行此操作。

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

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

[mutableDictionary addEntriesFromDictionary:dictionary];

0
投票

我建议使用常规for循环,而只是在索引处使用object,或者只是创建自己的计数器并执行相同的操作。但是如果你想保留foreach并且不想制作自己的计数器,你可以这样做:

[self.myDict setObject:[myStrings objectAtIndex:[myKeys indexOfObject:key]] 
                forKey: key];

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

有关并发循环的更多信息,请参阅这篇文章:When to use NSEnumerationConcurrent

© www.soinside.com 2019 - 2024. All rights reserved.