Objective-C enumerateUsingBlock vs fast enumeration?

lms*_*lms 35 objective-c

以下两种方法的优点和缺点是什么:

enumerateUsingBlock

NSArray *myArray = [NSArray new];
[myArray enumerateObjectsUsingBlock:^(id anObject, NSUInteger idx, BOOL *stop) {
    if (anObject == someOtherObject) {
        [anObject doSomething:idx];
        *stop = YES;
    }
}];
Run Code Online (Sandbox Code Playgroud)

快速列举

NSArray *myArray = [NSArray new];
int idx = 0
for (id anObject in myArray) {
    if (anObject == someOtherObject) {
        [anObject doSomething:idx];
        break;
    }
    ++idx;
}
Run Code Online (Sandbox Code Playgroud)

Sim*_*ker 47

这篇博客文章涵盖了主要的差异.综上所述:

  • OS X 10.5+提供快速枚举,10.6+提供块
  • 对于简单枚举,快速枚举比基于块的枚举快一点
  • 使用基于块的枚举进行并发或反向枚举比使用快速枚举更容易(并且更高效)
  • 枚举时,NSDictionary您可以使用基于块的枚举器获取键和值,而使用快速枚举时,您必须使用键在单独的消息发送中检索值.

关于最后一点(NSDictionary枚举),比较一下:

for (id key in dictionary)
{
    id obj = [dictionary objectForKey: key];
    // do something with key and obj
}
Run Code Online (Sandbox Code Playgroud)

对此:

[dictionary enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
    // do something with key and obj
}];
Run Code Online (Sandbox Code Playgroud)

此外,这两种方法都保护可变集合免受枚举循环内的变异.有趣的是,如果你试图在基于块的枚举中改变集合,你会得到CoreFoundation抛出的异常__NSFastEnumerationMutationHandler,这表明有一些常见的代码.

 NSMutableArray *myArray = [NSMutableArray arrayWithObjects:@"a", @"b", nil];
 [myArray enumerateObjectsUsingBlock:^(id anObject, NSUInteger idx, BOOL *stop) {
     // Attempt to mutate the array during enumeration
     [myArray addObject:@"c"];
 }];
Run Code Online (Sandbox Code Playgroud)

输出:

2011-12-14 22:37:53.716 Untitled[5809:707] *** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x109614190> was mutated while being enumerated.'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff8cca7286 __exceptionPreprocess + 198
    1   libobjc.A.dylib                     0x00007fff8319ad5e objc_exception_throw + 43
    2   CoreFoundation                      0x00007fff8cd311dc __NSFastEnumerationMutationHandler + 172
    3   CoreFoundation                      0x00007fff8cc9efb4 __NSArrayEnumerate + 612
    4   Untitled                            0x00000001094efcea main + 250
    5   Untitled                            0x00000001094efbe4 start + 52
    6   ???                                 0x0000000000000001 0x0 + 1
)
terminate called throwing an exceptionRun Command: line 1:  5809 Abort trap: 6           ./"$2"
Run Code Online (Sandbox Code Playgroud)