ios学习积累iOS 深度好文

oc循环break:continue,return,goto

2015-12-31  本文已影响1165人  sunflower1518

关键字:break:continue;return;goto;

enumerateObjectsUsingBlock

*stop

  NSArray *names = @[@"lzh", @"ysh", @"yys"];
  [names enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    if ([obj isEqualToString:@"lzh"]) {
        *stop = YES; // !!!这里并不会马上退出循环,而是执行完 block 中的代码才退出循环
    }
    NSLog(@"Name %@\n", obj);
  }];

return

NSArray *arr = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
[arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"Before if - obj = %@", obj);
    if ([obj isEqualToString:@"3"]) {
        return;      //仅跳出本次循环
    }
    NSLog(@"After if - obj = %@", obj);
}];

stop + return

NSArray *arr = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
[arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"Before if - obj = %@", obj);
    if ([obj isEqualToString:@"3"]) {
        *stop = YES;
        return;
        //stop 和 return配合使用,跳出本enum遍历
    }
    NSLog(@"After if - obj = %@", obj);
}];

双层循环,stop + return仅跳出本enum,对外层enum无影响

NSArray *arr = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
NSArray *arrson = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e", nil];
[arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"@@@@@@@@@@@@@@@@ Before if - obj = %@", obj);
        [arrson enumerateObjectsUsingBlock:^(id  _Nonnull objson, NSUInteger idxson, BOOL * _Nonnull stopson) {
            NSLog(@"---------------------Before if - obj = %@", objson);
            if ([objson isEqualToString:@"b"]) {
                *stopson = YES;
                return;
            }
            NSLog(@"------------After if - obj = %@", objson);
        }];
    NSLog(@"@@@@@@@@@@@@@@@@ After if - obj = %@", obj);
}];

https://lzhenhong.github.io/2016/09/08/enumerateObjectsUsingBlock/
http://www.jianshu.com/p/98d5eb51c29a

上一篇 下一篇

猜你喜欢

热点阅读