oc循环break:continue,return,goto

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

  • break:跳出本循环,比如本for循环

  • continue:跳出本循环体的本次循环,比如本for循环的i=2的这次循环

  • return:不但跳出所有循环体,连本方法都跳出了

  • goto,跳出到自己打标签的位置

    for(int i = 0; i < 3; i ++)
    {
      for(int j = 0; j < 3; j++)
      {
    
              if (i ==1 && j == 1 ) {
                  goto forEnd;
              }
              NSLog(@"%@-%@",@(i).stringValue, @(j).stringValue);
      }
    }
    forEnd:
    NSLog(@"--------会输出----------");
    

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

你可能感兴趣的:(oc循环break:continue,return,goto)