Pablo
Pablo

Reputation: 21

How to toggle on/off timer programmatically?

This is what I want to do: I want a timer to fire a method, and then in the end of this method, be toggled off and turn on an other timer on another method, and then entering a loop.

So what are the codes used to toggle between on and off the timer on a method?

In the Delphi programming language, I can use:

timer.Enabled := True; // timer.Enabled := False;

Is there a similar way to do it in Objective-C?

Upvotes: 1

Views: 1087

Answers (2)

Imirak
Imirak

Reputation: 1333

To turn the timer off, call invalidate on your timer like so:

[yourTimer invalidate]

And then to start a new one:

NSTimer *newTimer;
        
newTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 //Every how many seconds
                                            target:self
                                          selector:@selector(methodToCall)
                                          userInfo:nil
                                           repeats:YES];

Upvotes: 3

MikeS
MikeS

Reputation: 3921

Assuming your NSTimer is called "timer", you can use...

[timer invalidate]

to stop the timer. To make a timer pass a message to it's target method instantly, use

[timer fire]

To start a timer, you use one of the constructor methods listed in the documentation (https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html) such as

NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(doThisWhenTimerFires:) userInfo:nil repeats:NO]

- (void)doThisWhenTimerFires:(NSTimer *)timer
{
     //code here
}

Upvotes: 1

Related Questions