tags:

views:

730

answers:

3

Hello everyone. I'm programming an iPhone app and this is my question.

I have a NSTimer with an interval of 3 seconds that fires to decrease a value. In the other hand, when I do an action that increase that value I want to restart the timer to count from 3 seconds.

For example, if I increase the value and timer will fires on 1 second, I want to change it and set timer to fire on 3 seconds. May I invalidate timer and create it again?

I don't know if you understand me, I'm not english and I don't know if I explain it well.

Thank you very much.

edit: can i do it with setFireDate with current date and adding an interval of 3 seconds?

+2  A: 

Yes, you can invalidate it. And create it again.

You can also use:

- (void) myTimedTask {
    // other stuff this task needs to do

    // change the variable varyingDelay to be 1s or 3s or...  This can be an instance variable or global that is changed by other parts of your app
    // weStillWantTimer is also a similar variable that your app uses to stop this recurring task

if (weStillWantTimer)
       [self performSelector:@selector(myTimedTask:) withObject:gameColor afterDelay:varyingDelay];

 }

You call myTimedTask to start the recurring task. Once it is started, you can change the delay with varyingDelay or stop it with weStillWantTimer.

mahboudz
+1, but certainly not a *global*, right? :)
zoul
@zoul, depends on how messy you want to be :-)
mahboudz
A: 

Invalidate the timer and recreate it. However, make sure you don't invalidate and release the timer unless you are sure you need to since the run loop retains timers until they are invalidated and then releases them itself.

In my opinion mixing -performSelector code with timer code leads to multiple execution of the target methods, so I'd stay away from that.

Ben Lachman
A: 

Yes, invalidating and recreating the timer will work. It is essentially what you are wanting to do if you are not increasing your value: reset and start over.

mikestew