问题描述
除了明显的差异:
- 当你需要两者时,使用
enumerateObjectsUsingBlock
索引和对象 - 时,不要使用
enumerateObjectsUsingBlock
(我是错误的,请参阅bbum的答案)
- Use
enumerateObjectsUsingBlock
when you need both the index and the object - (I was wrong about this, see bbum's answer)
enumerateObjectsUsingBlock
通常认为更好或更糟糕的是, for(myArray中的id obj)
也可以吗?有什么优点/缺点(例如它或多或少都有效)?
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.
虽然的是相当的方便且语法简洁,
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 theNSFastEnumeration
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:
($ in ...)的频率高于,但是 - 再次 - 个人选择。
Personally, I use enumerateObjectsUsingBlock:
more often than for (... in ...)
, but - again - personal choice.
这篇关于何时使用enumerateObjectsUsingBlock vs.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!