gpt4 book ai didi

Objective-C enumerateObjectsUsingBlock vs 快速枚举?

转载 作者:太空狗 更新时间:2023-10-30 03:08:13 25 4
gpt4 key购买 nike

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

enumerate using block

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

fast enumeration

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

最佳答案

This blog post涵盖主要差异。总结:

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

关于最后一点(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
}];

此外,这两种方法都可以防止可变集合在枚举循环内发生突变。有趣的是,如果您尝试在基于 block 的枚举中改变集合,您会收到 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"

关于Objective-C enumerateObjectsUsingBlock vs 快速枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8509662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com