检测函数中的break语句?

时间:2015-06-30 12:15:31

标签: objective-c

我有以下功能:

- (void)doStuff {
    BOOL allDoneNow = NO;
    for (int i = 0; i < [arABFBmatches count]; i++) {
        for (int j = 0; j < [arABFBmatches count]; j++) {
            if (should_skip_rest) {
                allDoneNow = YES;
                break;
            }
        }
        if (allDoneNow) break;
    }
}

现在,如果我用[self doStuff];调用该方法,我该如何检测该函数是否破坏?或者有更好的方法来停止并重新启动函数的执行吗?

2 个答案:

答案 0 :(得分:1)

- (BOOL)doStuff // <- return a boolean value
{
  for (int i = 0; i < [arABFBmatches count]; i++) 
  {
    for (int j = 0; j < [arABFBmatches count]; j++) 
    {
      if (should_skip_rest) 
      {
        return NO;   // <- NO for break
      }
    }
  }
  return YES; // <- YES for completed
}

这使得函数的执行失败了。如果要重新启动它,只需在while循环中调用它。

while( (doStuff()==NO) && thereShouldBeAnotherConditionForStopping )
{
  // Do something after each attempt, otherwise it seems to be a little bit silly
}

答案 1 :(得分:0)

Or you can use blocks, like this:

- (void)doStuff:(void (^)())breakBlock{
    BOOL allDoneNow = NO;
    for (int i = 0; i < [arABFBmatches count]; i++) {
        for (int j = 0; j < [arABFBmatches count]; j++) {
            if (should_skip_rest) {
                allDoneNow = YES;
                breakBlock();
                break;
            }
        }
        if (allDoneNow) breakBlock();
    }
}

and call it:

[self doStuff:^{
    NSLog(@"ends with break");
}];