Creating an iPhone ApplicationAt a high level, the process for creating an iPhone application is similar to that for creating a Mac OS X application. Both use the same tools and many of the same basic libraries. Despite the similarities, there are also significant differences. An iPhone is not a desktop computer; it has a different purpose and requires a very different design approach. That approach needs to take advantage of the strengths of iPhone OS and forego features that might be irrelevant or impractical in a mobile environment. The smaller size of the iPhone and iPod touch screens also means that your application’s user interface should be well organized and always focused on the information the user needs most. iPhone OS lets users interact with iPhone and iPod touch devices in ways that you cannot interact with desktop applications. The Multi-Touch interface reports on each separate finger that touches the screen and making it possible to handle multifinger gestures and other complex input easily. In addition, built-in hardware features such as the accelerometers, although present in some desktop systems, are used more extensively in iPhone OS to track the screen’s current orientation and adjust your content accordingly. Understanding how you can use these features in your applications will help you focus on a design that is right for your users. The best way to understand the design of an iPhone application is to look at an example. This article takes you on a tour of the MoveMe sample application. This sample demonstrates many of the typical behaviors of an iPhone application, including:
Figure 1 shows the interface for this application. Touching the Welcome button triggers an animation that causes the button to pulse and center itself under your finger. As you drag your finger around the screen, the button follows your finger. Lift your finger from the screen and, using another animation, the button snaps back to its original location. Double-tapping anywhere outside the button changes the language of the button’s greeting. Figure 1 The MoveMe application window ![]() Before reading the other sections of this article, you should download the sample (MoveMe) so that you can follow along directly in the source code. You should also have already read the following orientation pages in the iPhone Dev Center to get a basic understanding of iPhone OS and the tools and language you use for development: If you are not familiar with the Objective-C programming language, you should also have read Objective-C Primer to familiarize yourself with the basic syntax of Objective-C. Examining the MoveMe Sample ProjectDownloading the MoveMe sample provides you with the source code and support files needed to build and run the application. You manage projects for iPhone OS using the Xcode application (located in Figure 2 shows the Xcode project window for the MoveMe application. To open this project, copy it to your local hard drive and double-click the Figure 2 The MoveMe project window ![]() In iPhone OS, the ultimate target of your Xcode project is an application bundle, which is a special type of directory that houses your application’s binary executable and supporting resource files. Bundles in iPhone OS have a relatively flat directory structure, with most files residing at the top level of the bundle directory. However, a bundle may also contain subdirectories to store localized versions of strings and other language-specific resource files. You do not need to know the exact structure of the application bundle for the purposes of this article, but you can find that information in “The Application Bundle” in iPhone Application Programming Guide if you are interested in it. Building the MoveMe ApplicationTo build the MoveMe application and run it in the simulator, do the following:
When the application finishes building, Xcode loads it into the iPhone simulator and launches it. Using your mouse, you can click the Welcome button and drag it around the screen to see the application’s behavior. If you have a device configured for development, you can also build your application and run it on that device. For information about how to configure devices for development and load applications, see iPhone Development Guide. A Word About Memory ManagementiPhone OS is primarily an object-oriented system, so most of the memory you allocate is in the form of Objective-C objects. iPhone OS uses a reference counting scheme to know when it is safe to free up the memory occupied by an object. When you first create an object, it starts off with a reference count of 1. Clients receiving that object can opt to retain it, thereby incrementing its reference count by 1. If a client retains an object, the client must also release that object when it is no longer needed. Releasing an object decrements its reference count by 1. When an object’s reference count equals 0, the system automatically reclaims the memory for the object. Note: iPhone OS does not support memory management using the garbage collection feature that is in Mac OS X v10.5 and later. If you want to allocate generic blocks of memory—that is, memory not associated with an object—you can do so using the standard Regardless of how you allocate memory, managing your overall memory usage is important. Although iPhone OS has a virtual memory system, it does not use a swap file. This means that code pages can be flushed as needed but your application’s data must all fit into memory at the same time. The system monitors the overall amount of free memory and does what it can to give your application the memory it needs. If memory usage becomes too critical though, the system may terminate your application. However, this option is used only as a last resort, to ensure that the system has enough memory to perform critical operations such as receiving phone calls. For more information about how to allocate objects in iPhone OS, see Cocoa Fundamentals Guide. For information and tips on how to improve your application’s memory usage, see “Using Memory Efficiently” in iPhone Application Programming Guide. Initializing the MoveMe ApplicationAs is true for every C-based application, the initial entry point for every iPhone application is a function called Listing 1 shows the Listing 1 Using the provided
Defining the Application DelegateOne of the most important architectural details of your project is defining the application delegate object, which is instantiated from a class you provide in your project. The application delegate class in MoveMe project declares its interface in To launch Interface Builder and see how the application delegate object’s role is defined, double-click the Figure 3 The application delegate ![]() The application delegate object works in tandem with the standard
At launch time, the most immediate concern for the delegate object is to set up and present the application window to the user, which is described in “Creating the Application Window”. The delegate should also perform any tasks needed to prepare your application for immediate use, such as restoring the application to a previous state or creating any required objects. When the application quits, the delegate needs to perform an orderly shutdown of the application and save any state information needed for the next launch cycle. For more information about the fundamental architecture and life cycle of an iPhone application, see “Core Application Architecture” in iPhone Application Programming Guide. Creating the Application WindowEvery application is responsible for creating a window that spans the entire screen and for filling that window with content. Graphical applications running in iPhone OS do not run side-by-side with other applications. In fact, other than the kernel and a few low-level system daemons, your application is the only thing running after it is launched. What’s more, your application should never need more than one window—an instance of the Windows provide the drawing surface for your user interface, but view objects provide the actual content. A view object is an instance of the At launch time, the goal is to create the application window and display some initial content as quickly as possible. The window is unarchived from the In the MoveMe application, the delegate’s
Listing 2 shows the Listing 2 Creating the content view
Note: You can use the applicationDidFinishLaunching: method to perform other tasks besides setting up your application user interface. Many applications use it to initialize required data structures, read any user preferences, or return the application to the state it was in when it last quit.Although the preceding code creates the window's background view and then shows the window, what you do not see in the preceding code is the creation of the Listing 3 Creating the placard view
For detailed information about creating windows and views, see “What Are Windows and Views?” in iPhone Application Programming Guide. Drawing the Welcome ButtonYou can use standard views provided by UIKit without modification to draw many types of simple content. For example, you can use the The By the time a view’s
Listing 4 shows the Listing 4 Drawing the Welcome button
When you need to draw content that is more complex than images and strings, you can use Quartz or OpenGL ES. Quartz works with UIKit to handle the drawing of vector-based paths, images, gradients, PDF, and other complex content that you want to create dynamically. Because Quartz and UIKit are based on the same drawing environment, you can call Quartz functions directly from the OpenGL ES is an alternative to Quartz and UIKit that lets you render 2D and 3D content using a set of functions that resemble (but are not exactly like) those found in OpenGL for Mac OS X. Unlike Quartz and UIKit, you do not use your view’s For detailed information about each of the drawing technologies and how you use them, see Graphics and Drawing in iPhone Application Programming Guide. Handling Touch EventsThe Multi-Touch interface in iPhone OS makes it possible for your application to recognize and respond to distinct events generated by multiple fingers touching the device. The ability to respond to multiple fingers offers considerable power but represents a significant departure from the way traditional, mouse-based event-handling systems operate. As each finger touches the surface of the device, the touch sensor generates a new touch event. As each finger moves, additional touch events are generated to indicate the finger’s new position. When a finger loses contact with the device surface, the system delivers yet another touch event to indicate that fact. Because there may be multiple fingers touching the device at one time, it is possible for you to use those events to identify complex user gestures. The system provides some help in detecting common gestures such as swipes, but you are responsible for detecting more complex gestures. When the event system generates a new touch event, it includes information about the current state of each finger that is either touching or was just removed from the surface of the device. Because each event object contains information about all active touches, you can monitor the actions of each finger with the arrival of each new event. You can then track the movements of each finger from event to event to detect gestures, which you can apply to the contents of your application. For example, if the events indicate the user is performing a pinch-close or pinch-open gesture (as shown in Figure 4) and the underlying view supports magnification, you could use those events to change the current zoom level. Figure 4 Using touch events to detect gestures ![]() The system delivers events to the application’s responder objects, which are instances of the
To simplify its own event-handling behavior, the MoveMe application tracks only the first finger to touch the surface of the device. It does this with the support of the As part of its event-handling behavior, the
Listing 5 shows the Listing 5 Handling an initial touch event
Listing 6 shows the Listing 6 Responding to movement from a touch
When the user’s finger finally lifts from the screen, the MoveMe application responds by triggering an animation to move the button back to its starting position in the center of the application’s window. Listing 7 shows the Listing 7 Releasing the Welcome button
To simplify the event handling process for the application, the If the application is interrupted for some reason—for example, by an incoming phone call—the view is sent a
For more information on handling events in iPhone OS, see Event Handling in iPhone Application Programming Guide. Animating the Button’s MovementIn iPhone applications, animation plays a very important role. Animation is used extensively to provide the user with contextual information and immediate feedback. For example, when the user navigates hierarchical data in a productivity application, rather than just replace one screen with another, iPhone applications animate the movement of each new screen into place. The direction of movement indicates whether the user is moving up or down in the hierarchy and also provides a visual cue that there is new information to look at. Because of its importance, support for animation is built into the classes of UIKit already. The MoveMe application takes advantage of this support by using it to animate the different aspects of the Welcome button. When the user first touches the button, the application applies an animation that causes the size of the button to grow briefly. When the user lets go of the button, another animation snaps it back to its original position. The basic steps for creating these animations are essentially the same:
Listing 8 shows the animation code used to pulse the Welcome button when it is first touched. This method sets the duration of the animation and then applies a transform to the button that scales it to its new size. When this animation completes, the animation infrastructure calls the Listing 8 Animating the Welcome button
For more information about using the built-in view-based animations, see “Animating Views” in iPhone Application Programming Guide. For more information about Core Animation, see “Applying Core Animation Effects” in iPhone Application Programming Guide. Finishing the ApplicationIn the preceding sections, you saw how the MoveMe application was initialized, presented its user interface, and responded to events. In addition to those aspects of the application creation, there are also smaller details that need to be considered before building an application and loading it onto a device. One of the final pieces to put in place is your application’s information property-list ( Listing 9 shows the contents of the Listing 9 The contents of the
Note: You can edit the contents of your application’s Info.plist file using TextEdit, which displays the XML contents of the file as shown in Listing 9, or the Property List Editor, which displays the file’s keys and values in a table. Xcode also provides access to some of these attributes in the information window for your application target. To view this window, select your application target (in the Targets group) and choose File > Get Info. The Properties tab contains some (but not all) of the properties in the Info.plist file.For information about configuring your application’s With this final piece in place, you now have all of the basic information needed to create your own functional iPhone application. The next step is to expand on the information you learned here by learning more about the features of iPhone OS. The applications you create should take advantage of the built-in features of iPhone OS to create a pleasant and intuitive user experience. Some of these features are described in “Taking Your Applications Further”, but for a complete list, and for information on how to use them, see iPhone Application Programming Guide. Taking Your Applications FurtherThere are many features associated with iPhone and iPod touch that users take for granted. Some of these features are hardware related, such as the automatic adjustment of views in response to a change in a device’s orientation. Others are software related, such as the fact that the built-in iPhone applications all share a single list of contacts. Because so many of the features described next are integral to the basic user experience, you should consider them during your initial design to see how they might fit into your application. Tracking Orientation and Motion Using the AccelerometersThe accelerometers in iPhone and iPod touch provide valuable input for the system and for your own custom applications. An accelerometer measures changes in velocity along a single linear axis. Both iPhone and iPod touch have three accelerometers to measure changes along each of the primary axes in three-dimensional space, allowing you to detect motion in any direction. Figure 5 Accelerometer axes ![]() Although you might not think measuring changes in acceleration would be very useful, in reality there is a lot you can do with the information. The force of gravity is constantly trying to pull objects to the ground. This force results in a measurable amount of acceleration toward the ground even when the device is at rest. By tracking which accelerometers are registering this acceleration, and the extent of that acceleration, you can detect the physical orientation of a device in 3D space with a fair amount of accuracy. You can then apply this orientation as input to your application. The system uses the accelerometers to monitor a device’s current orientation and to notify your application when that orientation changes. If your application’s interface can be displayed in both landscape and portrait mode, you should incorporate view controllers into your basic design. The If you want access to the raw accelerometer data directly, you can do so using the shared Accessing the User’s ContactsThe user’s list of contacts is an important resource that all system applications share. The Phone, Mail, and SMS Text applications use it to identify people the user needs to contact and to facilitate basic interactions such as starting a phone call, email, or text message. Your own applications can access this list of contacts for similar purposes or to get other information relevant to your application’s needs. Figure 6 Accessing the user’s contacts ![]() iPhone OS provides both direct access to the user’s contacts and indirect access through a set of standard picker interfaces. Using direct access, you can obtain the contact information directly from the contacts database. You might use this information in cases where you want to present contact information in a different way or filter it based on application-specific criteria. In cases where you do not need custom interface, however, iPhone OS also provides the set of standard system interfaces for picking and creating contacts. Incorporating these interfaces into your applications requires little effort but makes your application look and feel like it’s part of the system. You access the user’s contact information using the Address Book and Address Book UI frameworks. For more information about these frameworks, see Address Book Framework Reference and Address Book UI Framework Reference. Getting the User’s Current LocationDevices that run iPhone OS are meant for users on the go. Therefore the software you write for these devices should also take this fact into account. And because the Internet and web make it possible to do business anywhere, being able to tailor information for the user’s current location can make for a compelling user experience. After all, why list coffee shops in New York for someone who is thirsty and currently in Los Angeles? That’s where the Core Location framework can help. The Core Location framework monitors signals coming from cell phone towers and Wi-Fi hotspots and uses them to triangulate the user’s current position. You can use this framework to grab an initial location fix only, or you can be notified whenever the user’s location changes. With this information, you can filter the information your application provides or use it in other ways. For an example of how to get location data in your application, see “Getting the User’s Current Location” in iPhone Application Programming Guide. Playing Audio and VideoiPhone OS supports audio features in your application through the Core Audio and OpenAL frameworks, and provides video playback support using the Media Player framework. Core Audio provides an advanced interface for playing, recording, and manipulating sound and for parsing streamed audio. You can use it to play back simple sound effects or multichannel audio, mix sounds and position them in an audio field, and even trigger the vibrate feature of an iPhone. If you are a game developer and already have code that takes advantage of OpenAL, you can use your code in iPhone OS to position and play back audio in your games. The Media Player framework is what you use to play back full-screen video files. This framework supports the playback of many standard movie file formats and gives you control over the playback environment, including whether to display user controls and how to configure the aspect ratio of video content. Game developers might use this framework to play cut scenes or other prerendered content, while media-based applications can also use this framework to play back movie files. Figure 7 Playing back custom video ![]() For information about the media technologies in iPhone OS, see Multimedia Support in iPhone Application Programming Guide. Taking Pictures with the Built-in CameraThe Camera application on iPhone lets users take pictures and store them in a centralized photo library, along with the other pictures they upload from their computer. And although the iPod touch has no camera, it does have a photo library to hold the user’s uploaded pictures. iPhone OS provides access to both of these features through the Figure 8 The iPhone camera ![]() The For information on how to use the picker interfaces, see “Taking Pictures with the Camera” in iPhone Application Programming Guide and “Picking a Photo from the Photo Library” in iPhone Application Programming Guide. Last updated: 2009-10-12 |