while loop using NSTimer

2019-08-11 11:33发布

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

2条回答
祖国的老花朵
2楼-- · 2019-08-11 11:40

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.

查看更多
来,给爷笑一个
3楼-- · 2019-08-11 12:04

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
}
查看更多
登录 后发表回答