这是我试图开始工作的代码片段,但它的循环不会停止我想要的方式:
- (IBAction)methodName:(UIButton*)sender
{
[self loopMethod];
}
-(void) loopMethod
{
for( int index = 0; index < loopLimit; index++ )
{
//code I want to execute
[self performSelector:@selector(loopMethod)
withObject:nil
afterDelay:2.0];
}
}
代码只是保持循环,即使我已经使for循环有限。我想要的是执行代码,暂停两秒钟,然后在int
值小于我设置的loopLimit
时运行循环。
有人暗示这种performSelector:withObject:afterDelay:
方法可能不适合在这里使用,但我不确定为什么或在这里使用什么更好。
任何有启发性的建议?
答案 0 :(得分:3)
这里发生的事情是循环尽可能快地运行,并且performSelector:...
调用正以该速度发生。然后,在2.0001,2.0004,2.0010 ......秒之后,method
被调用。
另一件事(现在您已编辑以明确performSelector:...
最终调用与其相同的方法)是您的循环index
变量的值不是保存在调用之间。每次运行loopMethod
时,循环中的代码从头开始:index
设置为零并向上计数。这意味着每次运行该方法时,您最终都会随着loopLimit
新的呼叫暂停,从那时起2秒。这些呼叫中的每一个反过来产生一个新的集合,依此类推,无限制地。
循环的每次运行实际上都是有限的,但循环不断运行。你需要一些方法来表示循环需要停止,并且你不能完全在循环方法中完成。您可以将计数器(您的index
变量)放入ivar中;这将使其值在loopMethod
的调用中保持不变,但我认为您希望查看重复的using an NSTimer
:
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(method:) userInfo:nil repeats:YES];
如果你将它粘在一个ivar中,你可以跟踪它发射的次数并在以后停止它。关于更新循环中的文本字段,已经有很多帖子,使用这样的计时器:https://stackoverflow.com/search?q=%5Bobjc%5D+update+text+field+timer
答案 1 :(得分:2)
它不会每2秒运行的原因是因为您正在循环运行,并在2秒延迟后拍摄该选择器。换句话说,循环之间没有延迟。如果我不得不猜测,它可能等待2秒,然后发射loopLimit
次,对吗?
为了让你的功能以你想要的方式工作,它需要递归。
-(void) methodName
{
if(index < loopLimit) {
//code you want to execute
[self performSelector:@selector(**methodName**) withObject:nil afterDelay:2.0];
}
index++;
}
这是一个非常尴尬的方法。 NSTimer
通常是您在这里使用的,然后您可以在完成后停止计时器。
在一个函数中,你可以像这样启动计时器:
[self setIndex:0];
[self setTimer:[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(method:) userInfo:nil repeats:YES]];
然后每次调用此方法:
-(void)method:(NSTimer *)timer {
if(index >= loopLimit) {
[[self timer] invalidate];
}
//Code you want to execute
}