Quote:
Originally Posted by Anonymous Username
I want a timer to only work when I hold down the button, and stop counting when you let go. Im using two IBActions one touch up inside and one touch down. The touch up invalidates the timer and the touch down starts one, is there a better way?
|
It depends on your needs. If you need the timer to start exactly at the moment the user presses down, then yes, creating a timer on touch down is the way to go.
If you can tolerate a little slop, you could have a repeating timer running all the time, with the code the timer calls turned on and off by a BOOL instance variable. Let's call it timerActive.
On touch down, you'd set timerActive to true. On touchUp, you'd set timerActive to false.
The code that decrements your counter and displays the result would be inside an if statement: ("If (timerActive) {decrement counter and display}")
That approach would cause the first interval to be short sometimes, since the timer will already be "in flight" when the user presses the button.
I'd say since you've already done the work to create a new timer on touch down, and kill it on touch up, keep that approach. It's more accurate, but a little more work to set up. The work is done, so why do more work to implement a less accurate method? Just make sure your logic will never try to invalidate an already invalidated timer. That will cause a crash. I'd suggest setting your timer's instance variable to nil when you invalidate it.