USING THE NSTIMER CLASS

One of the easiest ways to get started with animation is to use the NSTimer class. The NSTimer class creates timer objects, which enable you to call a method at a regular time interval. Using an NSTimer object, you can update the position of an image at regular time intervals, thereby creating the impression that it is being animated.

In the following Try It Out, you learn how to display a bouncing ball on the screen using the NSTimer class. When the ball touches the sides of the screen, it bounces off in the opposite direction. You also learn how to control the frequency with which the ball animates. Download the code files indicated for this and other Try It Out features within this chapter.

TRY IT OUT: Animating a Ball

image

  1. Using Xcode, create a new Single View Application (iPhone) project and name it Animation. You will also use the project name as the Class Prefix and ensure that you have the Use Automatic Reference Counting option unchecked.
  2. Drag and drop an image named tennisball.jpg to the Supporting Files folder in Xcode. When the Add dialog appears, check the Copy Item into the Destination Group's Folder (If Needed) option so that the image is copied into the project (see Figure 13-1).

    image

    FIGURE 13-1

  3. Select the AnimationViewController.xib file to edit ...

Get Beginning iOS 5 Application Development 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.