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.
}
}
}
答
这是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;
}
}
}
答
这是一种方式。这是其他C变体和其他语言的适用技术。
bool breakOuterLoop = false;
while(!breakOuterLoop)
{
for(NSArray *arr in twoThousandItems)
{
if(IFoundWhatIWasLookingFor)
{
// assign some stuff here
breakOuterLoop = true;
break;
}
}
}
到目前为止所有的建议,看起来准确。选择其中的任何一个都不会错。我建议的设计是让你想要摆脱它自己的功能/方法的部分,并从中返回。抽象是功能和面向对象编程的主要力量 - 使用它。 – bshirley 2012-02-23 18:35:17
因为这是一个语言问题,而不是os问题,因此被重新标记。 :) – Almo 2012-02-23 18:35:50
@bshirley我用'goto',尽管我对此有点怀疑。它只在整个应用程序的一个地方,所以我认为它很好。但是,由于一些代码设计的改变,我们可以切换到您的建议方法(这始终是我的第一选择)。 +1 – Jacksonkr 2012-02-25 17:48:46