NCoder
NCoder

Reputation: 335

Start & Stop Timer

I have a timer that calls a function every 10 seconds:

[NSTimer scheduledTimerWithTimeInterval:10.0
                                     target:self
                                   selector:@selector(checkForMessages)
                                   userInfo:nil
                                    repeats:YES];

It calls the function:

- (void)checkForMessages
{

    //do something here

}

Two questions:

  1. How do I stop the timer if needed?
  2. Can I put this timer and function somewhere so that I can call it from different view controllers?

Upvotes: 0

Views: 2891

Answers (1)

Michael Dautermann
Michael Dautermann

Reputation: 89509

"scheduledTimerWithTimeInterval" returns an "NSTimer" object.

If you hold onto that object (e.g. set and get it via a "property"), you can stop it via the NSTimer invalidate method.

And since you're asking for code, add this to your view controller's .h @interface:

@property (strong) NSTimer * messageTimer;

Then, in your view controller's .m file:

self.messageTimer = [NSTimer scheduledTimerWithTimeInterval:10.0
                                     target:self
                                   selector:@selector(checkForMessages)
                                   userInfo:nil
                                    repeats:YES];

Makes sense?

Upvotes: 1

Related Questions