Chapter 31

Basic Animation with Timers

A timer is an object that waits for a time interval and then sends a specific message to a target object. When a timer sends the message, the act is generally referred to as firing, and the timer is said to have fired. You can set up a timer to be repeating or non-repeating. A non-repeating timer fires only once; a repeating timer fires and then reschedules itself to fire again.

In iOS development, timers are represented by instances of the NSTimer class. Timers have several uses, but in this lesson you learn to use them to create a simple animation.

Creating a repeating or non-repeating timer is simple and can be done by sending the scheduleTimerWithTimeInterval:target:selector:userInfo:repeats: class method to the NSTimer class:

NSTimer* animationTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 
                                   target:self
                                   selector:@selector(onTimerFired:) 
                                   userInfo:nil 
                                   repeats:YES];

The first parameter to this method is the time interval after which the timer should fire, expressed in milliseconds. If the timer is repeating, this is also the interval that will be used to reschedule the timer after it has fired.

The second parameter is the object to which a message should be sent when the timer fires. When used within view controllers, it is common to provide self for this value. The third parameter is the name of the message that should be sent to the target object. The object must implement a method that corresponds to the message. The method must be ...

Get iPhone and iPad App 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.