iOS / Objective-c – Simple NSTimer

Here’s a simple use of NSTimer to repeatedly trigger a method call every X seconds in Objective-c, for iOS.

Declare NSTimer variable in header file

NSTimer *myTimer;

Initialise myTimer at the appropriate point in code. Could be viewDidLoad on iPhone or willActivate on Apple Watch. My example triggers the method named updateDisplay at 5 second intervals. Note that I’ve set repeats: YES.
You can trigger the method for a one off call after X seconds by setting repeats: NO.

myTimer= [NSTimerscheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(updateDisplay)
userInfo:nil
repeats:YES];

The above code both primes and starts the timer.

To end the timer. Could be didDeactivate on apple Watch, for example

[myTimer invalidate];
myTimer = nil;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s