This blog post 涵盖了主要差异。总结:
- 快速枚举在 OS X 10.5+ 上可用,块在 10.6+ 上可用
- 对于简单枚举,快速枚举比基于块的枚举要快一些
- 使用基于块的枚举进行并发或反向枚举比使用快速枚举更容易(并且性能更高)
- 在对
NSDictionary 进行枚举时,您可以使用基于块的枚举器一次性获取键和值,而使用快速枚举时,您必须使用键在单独的消息发送中检索值。
关于最后一点(NSDictionary 枚举),比较一下:
for (id key in dictionary)
{
id obj = [dictionary objectForKey: key];
// do something with key and obj
}
到这里:
[dictionary enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
// do something with key and obj
}];
此外,这两种方法都可以防止可变集合在枚举循环中发生突变。有趣的是,如果您尝试在基于块的枚举中改变集合,您会收到 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"];
}];
输出:
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"