How to create an NSTimer

- by

Timers are good if you want to delay executing a method, or if you need to call a method repeatedly. To set a one-off timer without setting a property you can use this:

// calls the updateLabel method in 5 seconds
[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(updateLabel) userInfo:nil repeats:NO];

However, you won’t be able to stop it without a reference. This is fine for one-off timers, but you need one if you want to stop a repeating timer.

To start a repeating timer self.myTimer:

// calls the updateLabel method every 0.1 seconds
self.myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];

And to stop if:

// stop the timer
[self.myTimer invalidate];

Here’s a working example on GitHub: https://github.com/versluis/TimerFun



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.