【问题标题】:while loop using NSTimer使用 NSTimer 的 while 循环
【发布时间】:2013-09-07 22:57:32
【问题描述】:
我想创建一个运行 10 分钟的 NSTimer。然后我想在之后的行执行之前延迟 10 分钟的时间后编写一个 while 循环。例如。
NSTimer * countDown = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector userInfo:nil repeats:NO];
while (countDown == stil running (hasnt reached 10 minute mark) ){
// kill 10 minutes of time
}//when 10 minutes is up
execute next line of code
【问题讨论】:
标签:
ios
while-loop
nstimer
【解决方案1】:
第一
scheduledTimerWithTimeInterval: 方法的 timeInterval 参数以秒为单位。如果你想在几分钟内,别忘了乘以60。
第二
你为什么要像那样等待倒计时?只需在 NSTimer 触发的选择器中调用您想要在 10 分钟后执行的行。
NSTimer * countDown = [NSTimer
scheduledTimerWithTimeInterval:(10.0 * 60)
target:self
selector:@selector(tenMinutesLater)
userInfo:nil
repeats:NO];
然后
-(void)tenMinutesLater
{
//put some code here. This will be executed 10 minutes later the NSTimer was initialized
}
【解决方案2】:
只需在第一个计时器调用的方法中创建一个新计时器,而不是 while 循环。
NSTimer *countDown = [NSTimer scheduledTimerWithTimeInterval:600 target:self selector:@selector(startSecondTimer) userInfo:nil repeats:NO];
- (void)startSecondTimer
{
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:600 target:self selector:@selector(doSomething) userInfo:nil repeats:NO];
}
PS,时间间隔以秒为单位 - 10 分钟 = 600 秒,而不是 10 秒。