Using NSTimer in a Loop

僤鯓⒐⒋嵵緔 提交于 2019-12-20 07:14:29

问题


I need to show a timer counting down from 30 to 0, several times. (30 to 0, start over at 30, etc) However when I placed it in a for-loop, instead of waiting till the timer invalidates to begin the next timer, the loop iterates through and several timers are created.

How can I form a loop that waits until the timer has invalidated?

- (IBAction)startCountdown:(id)sender {

    NSNumber *rounds = [[NSNumber alloc]initWithInt:sliderRounds.value];
    for (int i = rounds.intValue; i > 0; i--) {
        [self timer];
}

回答1:


You can use the scheduledTimerWithTimeInterval

[NSTimer scheduledTimerWithTimeInterval: 0.5
             target: self
             selector: @selector(handleTimer:)
             userInfo: nil
             repeats: NO];

And inside the handleTimer you create the next timer




回答2:


Looks like you are calling some method called 'timer' on self. What does it do? Creates a new timer? Then this is why. When a timer is created, it doesn't block. Instead a method call is scheduled and executed once the timer timeout passes.




回答3:


What you could do is the following:

  • Create a class that holds an NSTimer
  • This class would have a variable to hold how many times it needs to count
  • At the end of one timer (and really, the only one) firing, it decrements the count

You can have the NSTimer repeat by calling it with:

[NSTimer scheduledTimerWithTimeInterval:30.0f
                             target:self 
                           selector:@selector(timerFired)
                           userInfo:nil
                            repeats:YES];

In a method called - (void)timerFired, you would decrement the count. If it reaches zero, you would stop the timer.

Hope this helps!



来源:https://stackoverflow.com/questions/4590524/using-nstimer-in-a-loop

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