ios - 为什么是 NSEnumerationReverse 而不是 NSEnumerationForward

标签 ios objective-c nsarray objective-c-blocks enumeration

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

- (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts
                         usingBlock:(void (^)(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.

NOW 通常循环写成 -

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

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

反向循环数组是否有性能优势?或者我没有正确理解NSEnumerationReverse

最佳答案

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

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

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

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

相关文章:

objective-c - UIWebView 向下滚动输入焦点仅限 iOS 6

objective-c - 在数组中搜索 NSRange 的字符串

objective-c - NSArray 的不区分大小写的 indexOfObject

ios - NSArray 按组枚举

ios - 使用 DragGesture 调整 SwiftUI View 的框架会在所有维度上调整其大小

ios - 在 ARC 系统中使用 openUDID

objective-c - ios gtm-oauth 没有键盘

ios - 防止 View 滚动到导航栏

iOS 应用程序更新和用户默认值

ios - 在 'levelCompleted' 类型的对象上找不到属性 'id'