最近在看一本书《Effective OC 2.0》,今天看到有个tip是OC适中循环各自优劣性,作者最终推荐此块循环。
阅读时思考了下块循环是否方便实现内部循环终止外部循环的问题。
于是做了如下验证,代码如下:
1 // 2 // main.m 3 // 块循环最具优势! 4 // 5 // Created by LongMa on 2019/4/3. 6 // Copyright © 2019年. All rights reserved. 7 // 8 9 #import10 11 int main(int argc, const char * argv[]) {12 @autoreleasepool {13 NSMutableArray *lArr1 = [NSMutableArray array];14 NSMutableArray *lArr2 = [NSMutableArray array];15 for (int i = 0; i < 10; ++i) {16 [lArr1 addObject:@(i)];17 [lArr2 addObject:@(i)];18 }19 20 //反向遍历21 // [lArr1 enumerateObjectsWithOptions:(NSEnumerationReverse)22 // usingBlock:^( NSNumber* obj, NSUInteger idx, BOOL * _Nonnull stop) {23 // NSLog(@"%@,ind:%lu", obj,(unsigned long)idx);24 // if (idx == 90) {25 // *stop = YES;26 // }27 // }];28 29 30 //思考:里循环能否终止外循环?31 //A:可以实现!需要差异化小标和停止参数,然后在里层循环对外循环的stopOut进行操作!此时,对内循环stopIn是否操作会决定内循环是否能执行完毕。32 33 /** 2019-04-03 01:08:30.003134+0800 块循环最具优势![3176:27943] 0,ind:034 2019-04-03 01:08:30.004040+0800 块循环最具优势![3176:27943] --0,ind:035 2019-04-03 01:08:30.004143+0800 块循环最具优势![3176:27943] --1,ind:136 2019-04-03 01:08:30.004679+0800 块循环最具优势![3176:27943] --2,ind:237 2019-04-03 01:08:30.004756+0800 块循环最具优势![3176:27943] --3,ind:338 2019-04-03 01:08:30.004819+0800 块循环最具优势![3176:27943] --4,ind:439 2019-04-03 01:08:30.004881+0800 块循环最具优势![3176:27943] --5,ind:540 2019-04-03 01:08:30.004914+0800 块循环最具优势![3176:27943] --6,ind:641 2019-04-03 01:08:30.004945+0800 块循环最具优势![3176:27943] --7,ind:742 2019-04-03 01:08:30.005036+0800 块循环最具优势![3176:27943] --8,ind:843 2019-04-03 01:08:30.005072+0800 块循环最具优势![3176:27943] --9,ind:9 */44 [lArr1 enumerateObjectsUsingBlock:^( NSNumber* obj, NSUInteger idxOut, BOOL * _Nonnull stopOut) {45 NSLog(@"%@,ind:%lu", obj,(unsigned long)idxOut);46 47 if (idxOut == 2) {48 *stopOut = YES;49 }50 51 [lArr2 enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idxIn, BOOL * _Nonnull stopIn) {52 NSLog(@"--%@,ind:%lu", obj,(unsigned long)idxIn);53 if (idxIn == 3) {54 *stopOut = YES;55 }56 }];57 }];58 59 /** 2019-04-03 01:05:20.987109+0800 块循环最具优势![3020:25596] 0,ind:060 2019-04-03 01:05:20.987380+0800 块循环最具优势![3020:25596] --0,ind:061 2019-04-03 01:05:20.987427+0800 块循环最具优势![3020:25596] --1,ind:162 2019-04-03 01:05:20.987476+0800 块循环最具优势![3020:25596] --2,ind:263 2019-04-03 01:05:20.987499+0800 块循环最具优势![3020:25596] --3,ind:3 */64 // [lArr1 enumerateObjectsUsingBlock:^( NSNumber* obj, NSUInteger idxOut, BOOL * _Nonnull stopOut) {65 // NSLog(@"%@,ind:%lu", obj,(unsigned long)idxOut);66 // 67 // if (idxOut == 2) {68 // *stopOut = YES;69 // }70 // 71 // 72 // [lArr2 enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idxIn, BOOL * _Nonnull stopIn) {73 // NSLog(@"--%@,ind:%lu", obj,(unsigned long)idxIn);74 // if (idxIn == 3) {75 // *stopIn = YES;76 // *stopOut = YES;77 // }78 // }];79 // 80 // }];81 82 83 }84 return 0;85 }
运行上面代码可见:
可以实现!需要差异化小标和停止参数,然后在里层循环对外循环的stopOut进行操作!此时,对内循环stopIn是否操作会决定内循环是否能执行完毕。