Adding time to NSTimer

356 views Asked by At

I'm creating an iOS test game as practice and want a game over method to be ran at the end of a 15 second timer.

I also want time to be added to this timer and taken away if certain actions take place.

Not having much luck figuring out how to add time or take away time from a certain timer depending on actions by the user.

So far I have the timer in viewDidLoad and a method with some conditional formatting that will do things depending on what the user does.

2

There are 2 answers

0
Paulw11 On

Once it has been created, the period of an NSTimer cannot be changed, the timer can only be cancelled or allowed to fire after the requested period.

In order to implement a timer for your game I would suggest that you set up a repeating timer that fires every second. The actual 'time remaining' value is stored in an integer and you decrement this value each time the timer fires. When this value reaches 0, end the game.

This way you can easily add additional time by simply changing the value of the time remaining variable.

This approach also makes it simple to display the remaining time on the screen.

0
Nikita Zernov On

Once NSTimer has been created, you cannot change time interval. But here's method I've done for me:

func addTimeToTimer(timer: NSTimer, time: NSTimeInterval, target: AnyObject, selector: Selector, repeats: Bool) -> NSTimer {
    let currentInterval = Float(timer.timeInterval)
    let targetInterval = NSTimeInterval(currentInterval + Float(time))

    let newTimer = NSTimer.scheduledTimerWithTimeInterval(targetInterval, target: target, selector: selector, userInfo: timer.userInfo, repeats: repeats)

    return newTimer
}

You will need to supply a lot of parameters because NSTimer does not store it all. Hope it helps.