SteveStifler
SteveStifler

Reputation: 154

Using NSTimer in a Loop

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];
}

Upvotes: 0

Views: 3383

Answers (3)

Bruno Domingues
Bruno Domingues

Reputation: 1015

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

Upvotes: 6

donkim
donkim

Reputation: 13137

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!

Upvotes: 0

Schultz9999
Schultz9999

Reputation: 8916

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.

Upvotes: 0

Related Questions