何时使用 enumerateObjectsUsingBlock 与 for [英] When to use enumerateObjectsUsingBlock vs. for

查看:19
本文介绍了何时使用 enumerateObjectsUsingBlock 与 for的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了明显的区别:

  • 当您需要索引和对象时使用 enumerateObjectsUsingBlock
  • 不要在需要修改局部变量时使用 enumerateObjectsUsingBlock(我错了,请参阅 bbum 的答案)

for (id obj in myArray) 也能工作时,通常认为 enumerateObjectsUsingBlock 是好是坏?有哪些优点/缺点(例如它的性能或多或少)?

Is enumerateObjectsUsingBlock generally considered better or worse when for (id obj in myArray) would also work? What are the advantages/disadvantages (for example is it more or less performant)?

推荐答案

最终,使用您想使用的任何模式,并且在上下文中更自然.

Ultimately, use whichever pattern you want to use and comes more naturally in the context.

虽然 for(... in ...) 非常方便且语法简洁,但 enumerateObjectsUsingBlock: 具有许多可能有趣也可能不有趣的特性:

While for(... in ...) is quite convenient and syntactically brief, enumerateObjectsUsingBlock: has a number of features that may or may not prove interesting:

  • enumerateObjectsUsingBlock: 将与快速枚举一样快或更快(for(... in ...) 使用 NSFastEnumeration代码>支持实现枚举).快速枚举需要从内部表示转换为快速枚举的表示.其中有开销.基于块的枚举允许集合类以最快的速度遍历本机存储格式来枚举内容.可能与数组无关,但对于字典可能会有很大差异.

  • enumerateObjectsUsingBlock: will be as fast or faster than fast enumeration (for(... in ...) uses the NSFastEnumeration support to implement enumeration). Fast enumeration requires translation from an internal representation to the representation for fast enumeration. There is overhead therein. Block-based enumeration allows the collection class to enumerate contents as quickly as the fastest traversal of the native storage format. Likely irrelevant for arrays, but it can be a huge difference for dictionaries.

当您需要修改局部变量时,不要使用 enumerateObjectsUsingBlock" - 不正确;您可以将本地变量声明为 __block 并且它们将在块中可写.

"Don't use enumerateObjectsUsingBlock when you need to modify local variables" - not true; you can declare your locals as __block and they'll be writable in the block.

enumerateObjectsWithOptions:usingBlock: 支持并发或反向枚举.

enumerateObjectsWithOptions:usingBlock: supports either concurrent or reverse enumeration.

对于字典,基于块的枚举是同时检索键和值的唯一方法.

with dictionaries, block based enumeration is the only way to retrieve the key and value simultaneously.

就个人而言,我使用 enumerateObjectsUsingBlock: 的频率高于 for (... in ...),但 - 再次 - 个人选择.

Personally, I use enumerateObjectsUsingBlock: more often than for (... in ...), but - again - personal choice.

这篇关于何时使用 enumerateObjectsUsingBlock 与 for的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆