Reputation: 685
I am currently making a application using NSTimer as base for recording time. However, in the event that the player used a hint or forfeit on the current question, I would like to have a penalty of increasing time to the on-going NSTimer.
The question I have is, is it possible to add in more value to the on-going NSTimer? e.g The timer is at 0:23:41.2, and the user press hint/forfeit. I want to have a function that add, lets say 10min. How do I make a function such that the timer will become 0:33:41.2 when the player press hint/forfeit?
I tried finding on google and SO on articles related to NSTimer and came across this SO thread which might be useful. How to value for NSTimer
Instead of elapse time as shown in the thread, I think I could swap it with a variable like below. (But if the example I shown below is not feasible, please enlighten me. I really want to make this game a successful one)
-(BOOL)hintButtonPressed
.
-(void) timerFireMethod:(NSTimer *) theTimer {
if (hintButtonPressed == true) {
// do something to increase value
[theTimer invalidate];
}
}
Upvotes: 0
Views: 299
Reputation: 1640
Even though I would not use a NSTimer for a countdown, there is an easy way to add time to its fireDate:
[_timer setFireDate:[[_timer fireDate] dateByAddingTimeInterval:600]];
This would add 10 minutes (600 seconds) to my _timer.
And the best solution for your example would be to create an action-method for the button and check in that action-method whether the user already got a time bonus.
Of course you can modify the fireDate in the fire method but it won't fire again with my codeline.
Upvotes: 2
Reputation: 3400
To what i remember, you can't add, increment time to a NSTimer, you need to create a new one, and release / invalidate the older one.
By the way, if it's a simple timer, you still can make it easy
[NSObject cancelPreviousPerformRequestsWithTarget: self]
[self performSelector:<#(SEL)#> withObject:<#(id)#> afterDelay: incrementedTime];
But you if you performSelector, you cant get precise time information like NSTimer, you can just blind increment time. So all depend of your needs.
Upvotes: 1
Reputation: 299265
NSTimer
is not a good tool for tracking time. It's a good tool for scheduling periodic actions (particularly actions that don't have very tight timing requirements).
The way you track time is with three ivars: the most recent "timer start" time, the "accumulated time" (which is the time prior to the most recent start), and an "isRunning" boolean. At any given time, the total time is:
accumulated + (now - start) * (isRunning ? 1 : 0)
With this, you can easily add or subtract time by modifying accumulated
. And you don't need an NSTimer
to update your data (which is seldom a good approach).
Upvotes: 2