前言
Block存在已久,Mac OSX10.6和iOS4.0以上系统都可以使用。 昨天偶然间看了一下Apple的官方文档,有一点恍然大悟的感觉:原来block还能这么用,惭愧惭愧。
使用block简化collection遍历
1. 先初始化一个array,备用:
NSMutableArray* numbers = [NSMutableArray array];
for (int i=0; i<10; i++) {
[numbers addObject:[NSNumber numberWithInt:i]];
}
2. 通常遍历这个array,我会这么写:
for (int i=0; i<[numberscount]; i++) {
NSLog(@"The object for index %d is %@", i, [numbersobjectAtIndex:i]);
}
int i=0;
for (NSObject* aobjin numbers) {
NSLog(@"The object for index %d is %@", i++, aobj);
}
int i=0;
for (NSNumber* aobjin numbers) {
NSLog(@"The object for index %d is %@", i++, aobj);
if ([aobjisEqual:[NSNumbernumberWithInt:3]]) {
[numbersremoveObjectAtIndex:i];
}
}
*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0xa1516c0> was mutated while being enumerated.'
*** First throw call stack:
(
0 CoreFoundation 0x017ee1e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x0156d8e5 objc_exception_throw + 44
2 CoreFoundation 0x0187dcf5 __NSFastEnumerationMutationHandler + 165
3 HelloBlks 0x0000327b -[ViewController enumerateBlock] + 667
4 HelloBlks 0x00002f22 -[ViewController setupUi] + 146
5 HelloBlks 0x00002e38 -[ViewController viewDidLoad] + 88
...
...
libc++abi.dylib: terminating with uncaught exception of type NSException
4. 终于有一天,我们认识了block
[numbersenumerateObjectsUsingBlock:^(id obj,NSUInteger idx, BOOL *stop) {
NSLog(@"The object for index %d is %@", idx, obj);
}];
很不情愿的在Xcode中输入了 numbers emu,这时提示出现了,按一下回车,再按一下回车,嗯,还不错:
[numbers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
<#code#>
}]
不到十个字母,再加上两个回车。
最重要的是,当我这么写的时候,居然没有听到一句抱怨:
[numbersenumerateObjectsUsingBlock:^(id obj,NSUInteger idx,BOOL *stop) {
NSLog(@"The object for index %d is %@", idx, obj);
if ([objisEqual:[NSNumbernumberWithInt:3]]) {
[numbersremoveObjectAtIndex:idx];
}
}];
本文探讨了在Objective-C中使用Block简化collection遍历的方法,对比了传统for循环和for...in循环的使用场景及注意事项,并介绍了Block如何避免在循环中修改集合导致的错误。
368

被折叠的 条评论
为什么被折叠?



