while loop using NSTimer

久未见 提交于 2019-12-11 08:14:40

问题


I want to create a NSTimer that runs for lets say 10 minutes. I then want to write a while loop aftewards delaying 10 minutes of time before the line afterwards is executed. For example.

     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

回答1:


First

The timeInterval parameter of scheduledTimerWithTimeInterval: method is in seconds. If you want in minutes, don't forget to multiply by 60.

Second

Why would you want to wait the countDown with a while like that? Just call the lines you want to execute 10 minutes later in the selector that NSTimer fires.

NSTimer * countDown = [NSTimer 
                        scheduledTimerWithTimeInterval:(10.0 * 60)
                        target:self 
                        selector:@selector(tenMinutesLater) 
                        userInfo:nil 
                        repeats:NO];

And then

-(void)tenMinutesLater
{
   //put some code here. This will be executed 10 minutes later the NSTimer was initialized
}



回答2:


Instead of a while loop, just make a new timer inside of a method called by your first timer.

 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, the time interval is in seconds - 10 mins = 600 seconds, not 10.



来源:https://stackoverflow.com/questions/18678715/while-loop-using-nstimer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!