Scheduling Events

You may want to add a timer to an app or to include a delay so a message is sent after a predetermined time. iOS includes basic timers and supports more complex scheduling options.

caution_exclamation_2c.eps

Timers have obvious applications—clocks, counters, sequence controllers—but occasionally, you’ll need to delay an event to give some other event time to finish. If your app seems to need this, you may need to rethink how it’s designed. Some time-based features in iOS, such as the animation classes, can automatically trigger a method when they complete. It’s better to make events happen in a clear order than to include arbitrary delays that guesstimate how long a process will take to finish.

Simple delays are built into iOS. You don’t need to create a timer to use them; you can trigger a method after a delay with a single line of code. Although you can use timer objects to achieve the same result, the single-method option is easier to work with.

Creating a simple delay

To trigger a method after a delay, do this:

[targetObject performSelector:

@selector(delayedMethod:) withObject: someObject afterDelay: a Delay];

If you don’t want to pass an object to the delayed method, replace “someObject” with “nil.” aDelay is a float—technically, an NSTimerInterval—set in seconds. You can use this feature with any method in any target object. Figure 7.9 shows a simple example. A method is used ...

Get iOS App Development Portable Genius now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.