Skip to content

Apple SDK – NSTimer

October 7, 2010

NSTimer is important within the iPhone, iPad, and Mac OS X for making any kind of time separation between method calls. If you have worked with javascript’s setTimeOut() method, then the NSTimer methods will look very familiar.

The idea of the NSTimer is that you ‘schedule’ a method invocation either some set date/time in the future, or a certain time interval in the future. As an example, you might have an NSTimer checking a web page every 5 seconds for updated content; something like this would probably be done using NSTimer.

An example…

In your viewDidLoad method:

myTimer = [NSTimer scheduledTimerWithTimeInterval: 5 target:self selector:@selector(someMethod) userInfo:nil repeats:YES]; // make sure to define this variable in your .h file

- (void) someMethod {
NSLog(@"Inside the method!");
// do something here... (called every 5 seconds)

All we’re doing above is scheduling a timer to ‘fire’ every 5 seconds, calling “someMethod” each time.

There’s the basic usage of NSTimer, there are a few other methods within the class, but “scheduledTimerWithTimeInterval:” seems to be the most important. Here’s Apple’s reference page for NSTimer:

Leave a Comment

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: