IOS破嵌套循环

问题描述:

如果我有一个while循环与for循环while循环,哪能break两个环?IOS破嵌套循环

我这样做是因为额外的250ms我没有完成这些循环后,我发现我想要的东西加起来有一段时间后有价值。

伪代码:

while(alwaysTrue) { 
    for(NSArray *arr in twoThousandItems) { 
     if(IFoundWhatIWasLookingFor) { 
      // assign some stuff here 
      // break everything, not just the for loop. 
     } 
    } 
} 
+3

到目前为止所有的建议,看起来准确。选择其中的任何一个都不会错。我建议的设计是让你想要摆脱它自己的功能/方法的部分,并从中返回。抽象是功能和面向对象编程的主要力量 - 使用它。 – bshirley 2012-02-23 18:35:17

+0

因为这是一个语言问题,而不是os问题,因此被重新标记。 :) – Almo 2012-02-23 18:35:50

+0

@bshirley我用'goto',尽管我对此有点怀疑。它只在整个应用程序的一个地方,所以我认为它很好。但是,由于一些代码设计的改变,我们可以切换到您的建议方法(这始终是我的第一选择)。 +1 – Jacksonkr 2012-02-25 17:48:46

这是goto是你的朋友。是的,那goto

while(alwaysTrue) { 
    for(NSArray *arr in twoThousandItems) { 
     if(IFoundWhatIWasLookingFor) { 
      // assign some stuff here 
      // break everything, not just the for loop. 
      goto BAIL; 
     } 
    } 
} 
BAIL: 
NSLog(@"Freedom!"); 

另一个选择是在你的循环中有短路。

while(alwaysTrue && !found) { 
    for(NSArray *arr in twoThousandItems) { 
     if(IFoundWhatIWasLookingFor) { 
      // assign some stuff here 
      // break everything, not just the for loop. 
      found = YES; 
      break; 
     } 
    } 
} 
+15

这是没有人的朋友,'goto'是邪恶的。 +1 – picciano 2012-02-23 18:39:22

+4

读过“goto”之后,似乎过度使用它是邪恶。虽然我是* @ bshirley *所提到的使用返回函数的更大粉丝,但是'goto'将适用于这种** **情况。感谢&+1 – Jacksonkr 2012-02-23 19:04:45

这是一种方式。这是其他C变体和其他语言的适用技术。

bool breakOuterLoop = false; 
while(!breakOuterLoop) 
{ 
    for(NSArray *arr in twoThousandItems) 
    { 
     if(IFoundWhatIWasLookingFor) 
     { 
      // assign some stuff here 
      breakOuterLoop = true; 
      break; 
     } 
    } 
}