【问题标题】:How to do fast enumeration to populate an NSDictionary using two NSArray's in Objective-C?如何在 Objective-C 中使用两个 NSArray 进行快速枚举以填充 NSDictionary?
【发布时间】:2014-01-24 17:46:02
【问题描述】:

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

【问题讨论】:

  • 您是否反对仅使用常规 for 循环并在控制变量的索引处执行对象?
  • 不,我不是,我只是想知道这是否可能。
  • + (instancetype)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys

标签: objective-c for-loop nsdictionary fast-enumeration


【解决方案1】:

查看文档,NSDictionary 无需枚举即可。

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

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

[mutableDictionary addEntriesFromDictionary:dictionary];

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      如果你真的想加快你的 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

      【讨论】:

      • 但是 NSDictionary 不是线程自身的。因此从多个线程同时修改self.myDictionary 可能会导致问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多