OGeek|极客世界-中国程序员成长平台

标题: ios - 为什么 NSEnumerationReverse 而不是 NSEnumerationForward [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 10:23
标题: ios - 为什么 NSEnumerationReverse 而不是 NSEnumerationForward

我正在研究循环遍历一个数组,我偶然发现了这种方法 --

- (void)enumerateObjectsWithOptionsNSEnumerationOptions)opts
                         usingBlockvoid (^)(id obj, NSUInteger idx, BOOL *stop))block

NSEnumerationOptions 定义为 -

enum {
   NSEnumerationConcurrent = (1UL << 0),
   NSEnumerationReverse = (1UL << 1),
};
typedef NSUInteger NSEnumerationOptions;

这些的描述来自NSHipster's blog post about enumeration --

NSEnumerationConcurrent: Specifies that the Block enumeration should be concurrent. The order of invocation is nondeterministic and undefined; this flag is a hint and may be ignored by the implementation under some circumstances; the code of the Block must be safe against concurrent invocation.

NSEnumerationReverse: Specifies that the enumeration should be performed in reverse. This option is available for NSArray and NSIndexSet classes; its behavior is undefined for NSDictionary and NSSet classes, or when combined with the NSEnumerationConcurrent flag.

现在循环通常写成 -

for ( int i=0 ; i< count; i++ )
{
   //stuff
}

我的问题是,为什么 NSEnumerationReverse 存在而 NSEnumerationForward 不存在。为什么 Apple 认为反向循环比从第一个索引循环更好。

反向循环遍历数组有性能优势吗?还是我没有正确理解 NSEnumerationReverse



Best Answer-推荐答案


声明的 NSEnumerationOptions 用于您想要使用非标准行为的时候——前向迭代是自动使用的默认行为除非您指定不同的选项。

要向前迭代,只需将 0 传递给枚举选项参数即可。

还要注意,由于无论如何您都为选项传递了零,因此您也可以只使用不接受任何选项的 enumerateObjectsUsingBlock: 方法,否则会执行完全相同的操作(并且打字更短)。

关于ios - 为什么 NSEnumerationReverse 而不是 NSEnumerationForward,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24205509/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4