iPhone Open Application Development
iPhone Open Application Development Write Native Objective-C Applications for the iPhone

By Jonathan A. Zdziarski
Book Price: $39.99 USD
£24.99 GBP
PDF Price: $27.99

Cover | Table of Contents | Forum | Colophon


Table of Contents

Chapter 1: Breaking Into and Setting Up the iPhone
The iPhone is a closed device. We can't say this enough. Up to and including version 1.1.x of the iPhone software, users have been locked out of the operating system. This doesn't seem to stop a majority of iPhone users, but does make it more difficult to get started. Before hacking of any kind can take place, however, the iPhone must be broken free from its jail—literally.
The iPhone runs in a chrooted environment, where no user or desktop application—even iTunes—can see into the operating system; this is commonly known in the Unix world as a chroot jail. This jail (and the fact that you can't simply yank out the hard drive) is the only thing standing in the way of the iPhone functioning as a complete, portable Mac OS X computer. Fortunately, many free tools have been written to make the jailbreaking process simple.
In this chapter, you'll stage your iPhone for software development. This includes breaking free from the chroot jail (called jailbreaking) so you can access the filesystem. You'll also install a BSD Unix world, which is a set of common Unix binaries such as ls and cp. This allows you to navigate and manage the iPhone's operating system, which is believed to be a version of Mac OS X 10.5 (Leopard) for the arm processor. Finally, you'll get a secure login command environment, SSH, up and running. This is useful for copying files to and from your iPhone, and we'll use it to install applications and run examples.
How you jailbreak your iPhone depends largely on what version of the software you are running. There is a lag time of a few weeks between new iPhone software releases and public hacks to jailbreak them. Small changes are generally introduced in new versions to make breaking into it a little bit harder each time. The good news is that once a new jailbreak has been written, all of the free tools available are updated to make it possible for just about anyone to go through the process.
There are many free tools available to jailbreak the iPhone, some more reliable than others. The best tools are full-service utilities that also allow you to set up a shell and install third party software with little effort. The best of breed tools include:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Jailbreak Procedures
How you jailbreak your iPhone depends largely on what version of the software you are running. There is a lag time of a few weeks between new iPhone software releases and public hacks to jailbreak them. Small changes are generally introduced in new versions to make breaking into it a little bit harder each time. The good news is that once a new jailbreak has been written, all of the free tools available are updated to make it possible for just about anyone to go through the process.
There are many free tools available to jailbreak the iPhone, some more reliable than others. The best tools are full-service utilities that also allow you to set up a shell and install third party software with little effort. The best of breed tools include:
iNdependence, (v1.0.0–1.1.3)
iNdependence is a utility for Mac OS X that performs jailbreak, activation, SSH installation, and even installation of ringtones, wallpaper, and third-party applications on the iPhone. iNdependence is under the GPL, and the author has made a library available called libPhoneInteraction, allowing developers to write other tools to communicate with the iPhone.
AppSnapp, (v1.1.1 only)
Users running version 1.1.1 of the iPhone firmware can navigate to this web site using their iPhone and have the entire jailbreak process performed remotely. AppSnapp takes advantage of a vulnerability in one of the iPhone's image libraries to break into the phone. What's cool about this site is that it not only jailbreaks your phone, but it also fixes the vulnerability so that nobody else can maliciously take advantage of the phone. Version 1.1.1 and later of AppSnapp also patch the iPhone software to allow third-party applications, and installs AppTapp, the NullRiver installer, which can then be used to stage your iPhone for development.
AppTapp, (v1.0.0–1.0.2)
Nullriver is a software manufacturer out of Ontario, Canada, and the designer of a package installer for the iPhone. Installer allows you to install any application on your iPhone that is included in their repository using a few easy taps. The installer software itself works with most versions of the iPhone software, but the installer's installer (if that makes sense) is capable only of jailbreaking iPhone firmware v1.0.x. The previous tool in this list, AppSnapp, automatically installs AppTapp on v1.1.1 devices. AppTapp is also useful for the software downgrade procedure, explained next.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing BSD Subsystem
Being able to access a shell on your iPhone is of little use without a Unix world to provide the basic commands. The installer application has a package called BSD Subsystem in the System category. This is a collection of Unix commands that will allow you the same basic Unix functionality as a desktop Unix system such as Mac OS X or Linux. Choose and install this package through the installer.
Congratulations, you're now ready to enter the world of iPhone applications development!
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Additional Resources
iPhone software is updated periodically by Apple, and so we can't document how every version of the software will act—especially newer versions that will be released after this book's publish date. To get the latest information about jailbreaking your iPhone or installing the tools listed in this chapter, the following development teams' web sites are invaluable resources:
iPhone Dev Team ()
The official site for the iPhone dev team, responsible for all known v1.1.x jailbreaks to date.
iPhone Elite Team ()
The iPhone Elite Team is another group of developers working primarily on unlocking and other hacks. They service the iPhone Utility Client and other tools.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Getting Started with Applications
If you're new to Mac, you might be surprised to find that applications don't come in the form of .EXE files. The excellent design for which Apple is known in its hardware and graphics extends into its software architecture as well, and includes the way applications are laid out in the file system. The same strategy used in Apple desktop systems carries over into the iPhone.
Apple has adopted the practice of creating modular, self-contained applications with their own internal file resources. As a result, installing most applications is as easy as simply dragging them into your applications folder; deleting them as easy as dragging them into the trash. In this chapter, the structure of applications on the iPhone will be explained. You'll also get up and running with the free open source tool chain used to build executables, and you'll learn how to install applications on your iPhone. Finally, you'll be introduced to the Objective-C language and enough of its idiosyncrasies to make an easy transition from C or C++.
Apple came up with an elegant way to contain applications in their operating system. As OS X is a Unix-based platform, Apple wanted to make it adhere to basic Unix file conventions, and so the resource forks of olde were no longer sufficient (or efficient for that matter). The challenge was to design a structure that would allow an application to remain self-contained while surviving on a file system that didn't believe in cheapening its architecture with proprietary workarounds. The result was to treat an application as a bundle inside a directory and use standard APIs to access resources, execute binaries, and read information about the application.
If you look inside any Mac application, you'll find that the .app extension denotes not a file, but a directory. This is the application's program directory. Inside it is an organized structure containing resources the application needs to run, information about the application, and the application's executable binaries. A compiler doesn't generate this program directory structure, but only builds the executable binaries. So to build a complete application, it's up to the developer to create a skeleton structure that will eventually host the binary and all of its resources.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Anatomy of an Application
Apple came up with an elegant way to contain applications in their operating system. As OS X is a Unix-based platform, Apple wanted to make it adhere to basic Unix file conventions, and so the resource forks of olde were no longer sufficient (or efficient for that matter). The challenge was to design a structure that would allow an application to remain self-contained while surviving on a file system that didn't believe in cheapening its architecture with proprietary workarounds. The result was to treat an application as a bundle inside a directory and use standard APIs to access resources, execute binaries, and read information about the application.
If you look inside any Mac application, you'll find that the .app extension denotes not a file, but a directory. This is the application's program directory. Inside it is an organized structure containing resources the application needs to run, information about the application, and the application's executable binaries. A compiler doesn't generate this program directory structure, but only builds the executable binaries. So to build a complete application, it's up to the developer to create a skeleton structure that will eventually host the binary and all of its resources.
The program directory for an iPhone application is much less structured than desktop Mac applications. In fact, all of the files used by the application are in the root of the .app program folder.
drwxr-xr-x    root    admin    Terminal.app/
    -rw-r--r--    root    admin    Default.png
    -rw-r--r--    root    admin    Info.plist
    -rwxr-xr-x    root    admin    Terminal
    -rw-r--r--    root    admin    icon.png
    -rw-r--r--    root    admin    pie.png
The above reflects a very basic iPhone application called MobileTerminal. MobileTerminal is an open source terminal client for the iPhone, allowing the user to pull up a shell and work in a Unix environment (which also must be installed as third-party software). MobileTerminal illustrates all of the major components of an iPhone application:
Terminal.app
The directory that all of the application's resources reside in.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building the Free Tool Chain
As we discussed in , the iPhone began life as a closed platform. This originally meant that no developer tools were publicly available to build iPhone-native applications. There has been much speculation about whether Apple secretly hoped the community would break into the phone, thus bolstering its status among the geek community. Over the first few months of the iPhone's life, this is exactly what happened. The open source community successfully cracked the phone and began writing a tool chain to build applications. It has since been released as free software. The tool chain consists of a cross-compiler, a linker, an assembler, a C hook into the assembler called Csu, and class headers for Objective-C frameworks generated by a tool called class-dump.
The tool chain uses a cross-compiler, which is a compiler that runs on one machine (namely, your desktop) but builds executables that can run on a different machine (the arm processor in an iPhone). The commands and path names provided throughout this book presume that you've used the procedures from this chapter to build and install the tool chain. The tool chain is updated periodically as new versions of it are released, so its setup can sometimes change. The instructions here will guide you through the steps to install version 0.30 of the tool chain, which is the latest available at the time of this writing. Newer versions are documented on the official tool chain project page at .
The tool chain builds and installs into /usr/local by default. All of the examples provided in this book will presume that this is where you've installed it. If you've built the tool chain before, or are just concerned about modifying files there, you'll want to move your current /usr/local out of the way and start with a fresh directory.
If you have a previous version of the tool chain, newer versions may not build correctly. To ensure that you start with a clean installation, move your old copy out of the way.
While there are some unofficial binary distributions of the tool chain floating around the Internet, you'll be building it from sources in this section. The following are requirements for building from sources.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building and Installing Applications
Now that the tool chain has been installed, the next step is to learn how to use it. There are two essential ways to build an executable: the command line or a makefile.
The examples in this book are simple enough that they can be built using the command line. The tool chain is compliant to standard compiler arguments, and should be familiar if you've ever used gcc in the past. You'll want to make sure /usr/local/bin is in your path before you try to use the cross-compiler.
$ export PATH=$PATH:/usr/local/bin
The anatomy of a typical command line compile is:
$ arm-apple-darwin-gcc -o MyExample MyExample.m -lobjc \
-framework CoreFoundation -framework Foundation
arm-apple-darwin-gcc
The name of the cross-compiler itself. This is located in /usr/local/bin, so be sure you've added it to your path.
-o MyExample
Tells the compiler to output the compiled executable to a file named MyExample.
MyExample.m
The name of the source file(s) being included in the program, separated by spaces. The .m extension tells the compiler that the sources are written in Objective-C.
-lobjc
Tells the compiler to link in the tool chain's Objective-C messaging library, which is needed by all iPhone applications. This library glues C-style function calls to Objective-C messages, among other things.
-framework CoreFoundation -framework Foundation
Two of the base frameworks to be linked into the application. Depending on what components of the operating system are being used in the code, different frameworks provide different layers of functionality. You'll be introduced to many different frameworks throughout this book.
The command line will suffice for most small applications and examples, but for larger applications, it makes sense to write a makefile. A makefile is a simple text file that acts as a manifest for building applications. It is used by a program called make, which is a portable build utility included with most development kits. The make program is responsible for calling the compiler (and linker) and passing them whatever flags and parameters are needed. Makefiles are logical ways to lay out the composition of an application. They also allow the developer to easily clean up the object files in a directory, create application packages, and perform a number of other tasks useful to building applications.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Integrating with XCode
While most developers use the command line or a makefile to build iPhone applications, the tool chain can be partially integrated with XCode to take advantage of the feature-rich editor and one-click build process. XCode treats the tool chain as an external resource and calls it to perform the actual build.
To integrate with XCode, a template is required to glue the necessary pieces to the tool chain. John Robinson from Monster and Friends has designed an XCode template based on one written by tool chain developer Lucas Newman. We've made some changes to tailor it to this book. Our version can be found in the download section for this book at . John's original version can be found at .
To integrate the cool chain with XCode, perform the following steps:
  1. Download and install XCode version 3.0 or later from Apple's developer web site.
  2. Download our version of the template from the O'Reilly web site and extract the archive's contents.
  3. A folder named iPhone UIKit Application will be created. Copy this directory into /Developer/Library/Xcode/Project Templates/Application on your Mac.
Once you've installed the template, you can now create a new iPhone project by performing these steps:
  1. Launch XCode and select New Project from the File menu. A list of templates will be presented to you to choose from.
  2. In the Application section of the list, scroll to the iPhone UIKit Application template and create a new project using it as the template.
A new project will now be created, and the project name will be reflected in the filenames used. To build the application, just click the Build button on the toolbar. XCode will call the tool chain's compiler and place a binary in the project's build folder.
Because XCode treats the tool chain as an external resource, it's not completely integrated with it. What happens under the hood is this: XCode kicks off a build process using a makefile present in the project template. This makefile calls the tool chain's compiler with the appropriate options. To add new files or frameworks to your project, you'll need to manually edit the file named
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Transitioning to Objective-C
Objective-C was written in the early 1980s by scientist and software engineer Brad Cox. It was designed as a way of introducing the capabilities of the Smalltalk language into a C programming environment. A majority of the iPhone's framework libraries are written in Objective-C, but because the language was designed to accommodate the C language, you can use C and C++ in your application as well. Objective-C is used primarily on Mac OS X and GNUstep (a free OpenStep environment). Many languages, such as Java and C#, have borrowed from the Objective-C language. The Cocoa framework makes heavy use of Objective-C on the Mac desktop, which carried over onto the iPhone.
If you've developed on the Mac OS X desktop before, you're already familiar with Objective-C, but if the iPhone is your first Apple platform, then you're likely transitioning from C or C++. This section will cover some of the more significant differences between these languages. If you have a prior background in C or C++, this should be enough to get you up and writing code using the examples in this book as a guide.
The first thing you'll notice in Objective-C is the heavy use of brackets. In Objective-C, methods are not called in a traditional sense; instead, they are sent messages. Likewise, a method doesn't return, but rather responds to the message. Unlike C, where function calls must be predefined, Objective-C's messaging style allows the developer to dynamically create new methods and messages at runtime. The downside to this is that it's entirely possible to send an object a message to which it can't respond, causing an exception and likely program termination.
Given an object named myWidget, a message can be sent to its powerOn method this way:
returnValue = [ myWidget powerOn ];
The C++ equivalent of this might look like:
returnValue = myWidget->powerOn(  );
The C equivalent might declare a function inside of its flat namespace:
returnValue = widget_powerOn(myWidget);
Arguments can also be passed with messages, provided that an object can receive them. The following example invokes a method named
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Introduction to UIKit
UIKit is the largest iPhone framework in terms of file size, and rightly so—it's responsible for all user interface functions from creating windows and text boxes to reading multitouch gestures and hardware sensors. All of the graphical pleasantries that make the iPhone seem easy-to-use rely on the UIKit framework to deliver a polished and unified interface. The same UIKit APIs are available to all iPhone applications, and understanding how to use this framework will allow you to take advantage of the same tools that make Apple's own stock apps spectacular.
UIKit is more than a mere user interface kit; it is also the runtime foundation for iPhone GUI applications. When an application is launched, its main( ) function instantiates a UIApplication object within UIKit. This class is the base class for all applications having a user interface on the iPhone, and it provides the application access to the iPhone's higher-level functions. In addition to this, common application-level services such as suspend, resume, and termination are functions of the UIApplication object.
To tap into the UIKit, your application must be linked to the UIKit framework. As a framework, UIKit is a type of shared library. So, using the compiler tool chain, UIKit can be linked to your application by adding the following arguments to the compiler arguments we described in :
$ arm-apple-darwin-gcc -o MyApp MyApp.m -lobjc \
    -framework CoreFoundation \
    -framework Foundation \
    -framework UIKit
To add this option to the sample makefile from the previous chapter, add the UIKit framework to the linker flags section so that the library is linked in:
LDFLAGS =    -lobjc \
        -framework CoreFoundation \
        -framework Foundation \
        -framework UIKit
This chapter is designed to get you up and running with a basic user interface. UIKit supports the following basic user interface elements. The more advanced features of UIKit are covered in .
Windows and views
Windows and views are the base classes for creating any type of user interface. A window represents a geometric space on a screen, while a view acts like a container for other objects. Smaller user interface components, such as navigation bars, buttons, and text boxes are all attached to a view, and that view is anchored to a window. Think of a window as the frame of a painting and the view as the actual canvas. A window can only frame up one view, but views can contain smaller subviews, including other views.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Basic User Interface Elements
This chapter is designed to get you up and running with a basic user interface. UIKit supports the following basic user interface elements. The more advanced features of UIKit are covered in .
Windows and views
Windows and views are the base classes for creating any type of user interface. A window represents a geometric space on a screen, while a view acts like a container for other objects. Smaller user interface components, such as navigation bars, buttons, and text boxes are all attached to a view, and that view is anchored to a window. Think of a window as the frame of a painting and the view as the actual canvas. A window can only frame up one view, but views can contain smaller subviews, including other views.
A controlling view is a view that controls how other views are displayed on the screen. The controlling view performs transitions to other views and responds to events occurring on the screen.
Text views
Text views are specialized view classes for presenting editor windows to view or edit text or HTML. The Notepad application is a good example of a simple text view. They are considered humble and are rarely used in light of UIKit's repertoire of more spectacular user interface tools.
Navigation bars
The iPhone user interface treats different screens as if they are "pages" in a book. Navigation bars are frequently used to provide a visual prompt to allow the user to return "back" to a previous view, supply them with buttons to modify elements on the current screen page, and provide formatted titles to the screen page they are viewing. Navigation bars are found in nearly all preloaded iPhone applications.
Transitions
A single screen page is rarely enough for any application to function, especially on a mobile device. Consistent with the spirit of Apple's user-friendly interfaces, window transitions were introduced with the iPhone to allow the user to perceive navigation through their application like pages in a book. Window transitions are used to make this visual transition from one window to another, and provide various types of different transitions from the familiar page flipping effect to fades and twists.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Windows and Views
The most basic user interface component is a window. A window is a region of screen space: a picture frame. UIWindow is the iPhone's base window class and is derived from lower level functions that respond to mouse events, gestures, and other types of events that would be relevant to a window. The UIWindow class is ultimately responsible for holding the contents of a UIView object (the picture that fits in the window's frame). UIView is a base class from which many other types of display classes are derived. The window itself can only hold one object, whereas the UIView object is designed to accommodate many different types of subobjects, including other views. The two classes go hand-in-hand with each other, and both are required to display anything on the iPhone screen.
Before you can display anything on the iPhone screen, you must create a window to hold content, and to build a window, you need a display region. A display region is a fancy term for rectangle and represents the portion of the screen where the window should be displayed. The underlying structure itself is a rectangle structure named CGRect that contains two pieces: the coordinates for the upper-left corner of the window and the window's size (its width and height). Every object displayed on the screen has a display region defining its display area. Most are set when the object is initialized, via an initWithFrame method. Others must be set after the fact using a ubiquitous method named setFrame. In the case of the main window, the region's coordinates are offset to the screen itself; however, all subsequent objects (including the window's view) are offset to the object that contains it. As other objects are nested inside the view, those objects' regions will be offset to the view, and so on.
An application uses the entire iPhone screen when it is displayed, and so the window should be assigned a set of coordinates reflecting the view region of the entire screen. This region can be obtained from a static method found inside a class named UIHardware.
CGRect windowRect = [ UIHardware fullScreenApplicationContentRect ];
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Most Useless Application Ever
Before we even get to "Hello, World!", we need an even more useless application, "Hello, Window!". This application does nothing more than to create a window and view pair. In fact, because the base UIView class is just a container class, it can't even display any text for you. All you'll see is a black screen. What this application does do is serve as the first few lines of code any GUI application on the iPhone will use.
This application, shown in and , can be compiled from the tool chain using the following command line:
$ arm-apple-darwin-gcc -o MyExample MyExample.m -lobjc \
    -framework CoreFoundation -framework Foundation -framework UIKit
Example . Example window and view (MyExample.h)
#import <CoreFoundation/CoreFoundation.h>
#import <UIKit/UIKit.h>

@interface MyApp : UIApplication
{
    UIWindow *window;
    UIView *mainView;
}
- (void)applicationDidFinishLaunching:
    (NSNotification *)aNotification;
@end
Example . Example window and view (MyExample.m)
#import "MyExample.h"

int main(int argc, char **argv)
{
    NSAutoreleasePool *autoreleasePool = [
        [ NSAutoreleasePool alloc ] init
    ];
    int returnCode = UIApplicationMain(argc, argv, [ MyApp class ]);
    [ autoreleasePool release ];
    return returnCode;
}

@implementation MyApp

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    window = [ [ UIWindow alloc ] initWithContentRect:
        [ UIHardware fullScreenApplicationContentRect ]
    ];

    CGRect windowRect =
        [ UIHardware fullScreenApplicationContentRect ];
    windowRect.origin.x = windowRect.origin.y = 0.0f;

    mainView = [ [ UIView alloc ] initWithFrame: windowRect ];

    [ window setContentView: mainView ];
    [ window orderFront: self ];
    [ window makeKey: self ];
    [ window _setHidden: NO ];
}
@end
The "Hello, Window!" application flows like this:
  1. When the application starts, its main( ) function is called, just as in a regular C program. This hooks into Objective-C land and instantiates an application class named MyApp, which is derived from UIKit's UIApplication class. The
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Deriving from UIView
The "Hello, Window!" example showed the very minimal code needed to construct and display a window/view pair. Because the UIView class itself is merely a base class, it didn't actually display anything. To create a useful application, a new class can be derived from UIView, allowing its methods to be overridden to add functionality. This controlling view can then display other objects, such as text boxes, images, etc.
To derive a subclass from UIView, write a new interface and implementation declaring the subclass. The following snippet creates a subclass named MainView:
@interface MainView : UIView
{

}

- (id)initWithFrame:(CGRect)rect;
- (void)dealloc;
@end
At the very least, two UIView class methods should be overridden. The initWithFrame method is called when the view is first instantiated and is used to initialize the view class. A display region is passed in to define its coordinates (offset to its parent) and size it should display as. Any code that initializes variables or other objects can go into this method. The second method, dealloc, is called when the UIView object is disposed of. Any resources previously allocated within your class should be released here.
These two methods are the basis for all other activity within the view class. Here are the templates for them:
@implementation MainView
- (id)initWithFrame:(CGRect)rect {

    if ((self == [ super initWithFrame: rect ]) != nil) {

        /* Initialize member variables here */

        /* Allocate initial resources here */
    }

    return self;
}

- (void)dealloc
{
    /* Deallocate any resources here */

    [ self dealloc ];
    [ super dealloc ];
}
@end
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Second Most Useless Application Ever
Now that you know how to derive a UIView class, you've got everything you need to write an application that does something—albeit a mostly useless something. In the tradition of our ancestors, we now present the official useless "Hello, World!" application.
This application, shown in and , can be built using the same command-line arguments as the previous example:
$ arm-apple-darwin-gcc -o MyExample MyExample.m -lobjc \
    -framework CoreFoundation -framework Foundation -framework UIKit
Example . "Hello World!" example (MyExample.h)
#import <CoreFoundation/CoreFoundation.h>
#import <UIKit/UIKit.h>
#import <UIKit/UITextView.h>

@interface MainView : UIView
{
        UITextView         *textView;
}
- (id)initWithFrame:(CGRect)frame;
- (void)dealloc;
@end

@interface MyApp : UIApplication
{
    UIWindow *window;
    MainView *mainView;
}
- (void)applicationDidFinishLaunching:
    (NSNotification *)aNotification;
@end
Example . "Hello World!" example (MyExample.m)
#import "MyExample.h"

int main(int argc, char **argv)
{
   NSAutoreleasePool *autoreleasePool = [
        [ NSAutoreleasePool alloc ] init
    ];
    int returnCode = UIApplicationMain(argc, argv, [ MyApp class ]);
    [ autoreleasePool release ];
    return returnCode;
}

@implementation MyApp

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    window = [ [ UIWindow alloc ] initWithContentRect:
        [ UIHardware fullScreenApplicationContentRect ]
    ];

    CGRect rect = [ UIHardware fullScreenApplicationContentRect ];
    rect.origin.x = rect.origin.y = 0.0f;

    mainView = [ [ MainView alloc ] initWithFrame: rect ];

    [ window setContentView: mainView ];
    [ window orderFront: self ];
    [ window makeKey: self ];
    [ window _setHidden: NO ];
}
@end

@implementation MainView
- (id)initWithFrame:(CGRect)rect {

    if ((self == [ super initWithFrame: rect ]) != nil) {

        textView = [ [ UITextView alloc ] initWithFrame: rect ];
        [ textView setTextSize: 18 ];
        [ textView setText: @"Hello, World!" ];
        [ self addSubview: textView ];
    }

    return self;
}

- (void)dealloc
{
    [ self dealloc ];
    [ super dealloc ];
}

@end
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Text Views
The UITextView class is based on a UIView, however, its functionality has been extended to present and allow editing of text, provide scrolling, and handle various fonts and colors. Text views can be easily abused, and are only recommended for text-based portions of an application, such as an electronic book, notes section of a program, or informational page to present unstructured information.
A UITextView object inherits from UIScroller, which is a generic scrollable class. This means that the text view itself comes pre-equipped with all scrolling functionality, so the developer can focus on presenting content rather than programming scroll bars. The UIScroller class inherits from UIView, which, as discussed in the last section, is the base class for all view classes.
Because UITextView is ultimately derived from UIView, it is created in the same fashion as the main view objects created in the last section—using an initWithFrame method.
UITextView *textView = [ [ UITextView alloc ]
    initWithFrame: viewRect ];
Once the view is created, a number of different properties can then be set.

Editing

If the text view is being used to collect user input, it will need to be made editable:
[ textView setEditable: YES ];
If the view is simply presenting data that should not be edited, this feature should be disabled.

Margins

The size of the top margin is the only margin that can be set in the text view. The value represents the number of pixels from the top of the text view that the text should be offset.
[ textView setMarginTop: 20 ];

Text properties

The text size, font and color can be set by passing point sizes and font and color objects into the class. These settings work for text and HTML uses, although they serve only as a default for HTML.
The text size is the simplest property, and is passed as an integer measuring point size.
[ textView setTextSize: 12 ];
The font is passed in as a CSS compliant string identifying the font properties.
[ textView setTextFont:
  @"font-family: Helvetica; font-style: italic; font-weight: bold" ];
The text color is a bit trickier and requires the use of another framework on the iPhone named Core Graphics. To create a simple RGB color, a set of four floating-point values for red, green, blue, and alpha (opacity) are specified with values between 0.0 and 1.0. These represent values ranging from 0% (0.0) to 100% (1.0). The values are used to create a color reference, which is then assigned in the text view as a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Navigation Bars
The iPhone doesn't support toolbars in the traditional desktop sense. Because each screen of an application is considered a page in a book, Apple has made their version of the toolbar for iPhone to appear more book-like as well. In contrast to toolbars, which can display a clutter of different icons, navigation bars are limited to include a page title (e.g., "Saved Messages"), directional buttons to parent pages, and text buttons for context-sensitive functions such as turning on the speakerphone or clearing a list of items. Navigation bars can also support controls to add tabbed buttons such as the "All" and "Missed" call buttons when viewing recent calls.
To create a navigation bar, instantiate it as an object and call its initWithFrame method—just like a UIView.
UINavigationBar *navBar = [ [UINavigationBar alloc]
    initWithFrame: CGRectMake(0, 0, 320, 48)
];
The above creates a navigation bar 48 pixels high (the default) at position 0x0 (the upper-left corner of its parent view). This is the general convention, but a navigation bar can be created anywhere within the window. By using a different vertical offset, you can place the navigation bar at the bottom of the window or underneath another navigation bar.
To know when something happens on the navigation bar, such as a button press, use the navigation bar's delegate. A delegate is an object that acts on behalf of another object. By setting the navigation bar's delegate to self, you can have it send events such as button presses to the object that created the navigation bar.
[ navBar setDelegate: self ];
Animations are simple fade transitions that occur when transitioning from an old set of buttons to a new set—for example, if a button is changed after it is pressed. Calling enableAnimation uses these smoother transitions instead of an instantaneous change.
[ navBar enableAnimation ];
Once the navigation bar has been created and initialized, its title and buttons can then be configured. These can be changed even after the navigation bar is displayed; the bar will change to accommodate its new settings.

Setting the title

Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Transition Views
If there's one thing Apple is well known for, it's their devotion to aesthetics in their user interfaces. The effect of sliding pages left and right gives the user a sense of the flow of data through an application, or a sense of "forward" and "back." Even applications lacking a book type of structure can appreciate the smooth slide and fade transitions offered by UIKit. Transition views are objects that allow the current view on the screen to be swapped out smoothly and replaced by another view, with very little programming on the developer's part.
Transition views inherit from UIView, so they have most of the properties of a regular view, including a frame. To create a transition, the display region belonging to the view is passed to the transition's initWithFrame method.
UITransitionView *transitionView = [ [ UITransitionView alloc ]
    initWithFrame: viewRect ];
The same transition view can be used for multiple transition calls and even multiple transition types, so generally only one transition view is needed for a particular display region. If a navigation bar is being used, you must account for its presence by subtracting its height and coordinates from the transition view's display region:
UITransitionView *transitionView = [ [ UITransitionView alloc ]
     initWithFrame:
     CGRectMake(viewRect.origin.x, viewRect.origin.y + 48.0,
            viewRect.size.width, viewRect.size.height − 48.0
];
Once the transition has been created, it is added to the view in the same way as other view objects, as a sublayer.
[ self addSubview: transitionView ];
To effect a transition, call the class's transition method. You'll supply the transition style and pointers to the two views between which you are transitioning.
[ transitionView transition: 0
  fromView: myOldView
  toView: myNewView
];
Alternatively, a transition can be called supplying only the new view, not the old one. But be forewarned that this appears to work with only some transitions. Those that do not support this behavior automatically default to using no transition.
[ transitionView transition: 0 toView: myNewView ];
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Alert Sheets
The iPhone is a relatively small device with limited screen space and no stylus. This means users are going to fumble with their fingers and tap buttons on accident. When this happens, a well-written application prompts the user for confirmation before just blowing away important data. On a desktop computer, applications pop up windows when they need attention. On the iPhone, an alert sheet is slid up from the bottom, graying out the rest of the screen until the user chooses an option. The term "sheet" continues the page metaphor that Apple uses for the iPhone.
The alert sheet is an object that can be instantiated on top of any view, and a single view can host a number of different alert sheets. A basic alert sheet consists of a title, body text, and whatever choices the user should be presented with. It is instantiated in the same way as other UIView objects, using an initWithFrame method. Because alert sheets appear at the bottom, the window's origin can begin halfway down the screen (Y = 240).
UIAlertSheet *alertSheet = [ [ UIAlertSheet alloc ]
    initWithFrame: CGRectMake(0, 240, 320, 240) ];
[ alertSheet setTitle:@"Computer doesn't like people" ];
[ alertSheet setBodyText: [ NSString stringWithFormat:
    @"I did not complete your request because I don't like humans." ]
];
[ alertSheet setDelegate: self ];
Alert sheets can stretch their frame to accommodate whatever elements it's required to hold, so a static 320×240 rectangle should be sufficient for standard alert sheets.
Like navigation bars, alert sheets can be set to support one of three different styles.
Style
Description
0
Default style, gray gradient background with white text
1
Solid black background with white text
2
Transparent black background with white text
The style can be set with a call to setAlertSheetStyle.
[ alertSheet setAlertSheetStyle: 0 ];
On rare occasion, it makes sense to display an alert sheet without buttons—for example, to display a progress bar (explained in ). In most cases, however, alert sheets are displayed for the purpose of prompting the user. An alert sheet can accommodate as many buttons as can fit on the screen. To add a button, call the alert sheet's
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tables
Tables are the foundation for most types of selectable lists on the iPhone. Voicemail, recent calls, and even email all use the feature-rich UITable class to display their lists of items. In addition to being a basic list selector, the UITable class includes built-in functionality to add disclosures, swipe-to-delete, animations, labels, and even images.
A table has three primary components: the table itself, table columns, and table cells (the individual rows in a table). The table's data is queried from a table's data binding. A data binding is an interface used by the table to query information about what data to display, such as filenames, email messages, etc. The data source is an object that responds to this query. When the table is created, a data source must be attached to it in order for the table to display anything. It gets called whenever the table is reloaded or new cells are scrolled into view and tells the table which columns and rows to display, along with the data within them.

Subclassing UITable

For most specialized uses, the table can serve as its own data source. This allows the table class and the table's data to be wrapped cleanly into a single class. To do this, subclass the UITable object to create a new class for your data. In the following example, a subclass named MyTable is created. The base class methods used to initialize and destroy the object are overridden to provide the table portion of the class:
@interface MyTable : UITable
{

}
-(id)initWithFrame:(struct CGRect)rect;
-(void) dealloc;
To add the data source portion of the class, two methods are used to make the table's data binding load data: numberOfRowsInTable and cellForRow. Because the table is acting as its own data source, you must write these methods into your subclass, where the methods will be responsible for returning column and row data for the table.
- (int)numberOfRowsInTable:(UITable *)_table;
- (UITableCell *)table:(UITable *)table
    cellForRow:(int)row
    column:(UITableColumn *)col;
We'll look at these methods later in the section "."

Overriding UITable methods

When creating a subclass of
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Status Bar Manipulation
The status bar's appearance can be customized to meet the look and feel of your application, and can also display notifications about your application. For instance, the iPod application uses the status bar to display a triangular play icon when music is playing in the background. The alarm clock application displays a small clock on the status bar when an alarm is active. Many properties of the status bar can be changed using the UIApplication and UIHardware classes.
The status bar mode determines its color, opacity, and orientation. It can also be used to animate the status bar when transitioning between different modes. To set the mode, one of four different setStatusBarMode methods can be used from within the instance of your application, a UIApplication object.
- (void)setStatusBarMode:(int)mode duration:(float)duration
- (void)setStatusBarMode:(int)mode orientation:(int)orientation
    duration:(float)duration
- (void)setStatusBarMode:(int)mode orientation:(int)orientation
    duration:(float)duration fenceID:(int)fenceID
- (void)setStatusBarMode:(int)mode orientation:(int)orientation
    duration:(float)duration fenceID:(int)fenceID
    animation:(int)animation;

Mode

The status bar mode sets the overall appearance in color and opacity. The following modes are supported.
Mode
Description
0
Default, white status bar
1
Black transparent status bar
2
Removes status bar image entirely (be sure to also use _setStatusBarSize)
3
Solid black status bar
4
Entirely transparent status bar
5
Flashing green status bar with "Touch to return to call" text
6
Red transparent status bar

Orientation

The orientation determines where the status bar is displayed on the iPhone's screen. If the iPhone is being held in a landscape fashion, the application may choose to re-orient itself to accommodate the wider display. The value passed with the orientation argument represents the angle at which the iPhone's screen will be displayed.
Angle
Description
0
Status bar is displayed at the natural top of the iPhone
90
Status bar is displayed in landscape across the right portion of the screen
−90
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Application Badges
With the iPhone's numerous different connections—EDGE, WiFi, and Bluetooth (not to mention the cellular network)—lots of things can happen while you've got that little device stuck in your pocket. Without some notification to the user that there are pending notifications, they're likely to miss everything that's happened while they were busy having a real life. Application badges are small message bubbles that appear on the program's SpringBoard icon. Application badges are used heavily by Apple's preloaded applications to alert the user to missed calls, voicemail, text messages, and email.
One of the nice features about these types of badges is that the application doesn't necessarily need to be running for the badge to display on the SpringBoard. This is useful in serving as a reminder to the user even after they've exited the application. This also means you'll need to clean up any lingering badges when your program exits.
Application badges are one of the easier features to take advantage of, requiring only one call to the UIApplication class.
 [ UIApp setApplicationBadge: @"Hi!" ];
The setApplicationBadge method takes an NSString object, which can be built with standard string formatting.
NSString *badgeText = [ [ NSString alloc ]
    initWithFormat:@"%d", numNewMessages ];
[ UIApp setApplicationBadge: badgeText ];
An application badge should be removed when the user has clicked to the page with the important events they were being notified about. Removing the application badge is also an easy task. A good place to put such code is after transitioning to the view with the events. For example:
[ transitionView transition: 0 toView: missedCalls ];
[ UIApp removeApplicationBadge ];
An application badge will continue to hang around even after an application has terminated. This can be useful, but it's not always what you want. If an application badge should be removed when the program exits, you'll also need to make a call to removeApplicationBadge in the application's applicationWillTerminate method.
- (void)applicationWillTerminate {
    /* We are about to exit, so remove the application badge */
    [ UIApp removeApplicationBadge ];
}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Application Services
The state of an application is more important on the iPhone than it is on the desktop. This is because many events on the iPhone can cause an application to suspend, run in the background, or terminate. These different states occur when the user presses the home button, locks the screen, or receives a phone call. It's important for an application to know when its state is about to change to save any settings, halt threads, or perform other actions.
The UIApplication base class contains many functions for application state changes, which can be overridden by the application. While there's nothing the application can generally do about the state it's about to enter, it can at least take whatever actions are appropriate to prepare for it.
When the home button is pressed, the default behavior for an application is to suspend. It's also told to suspend during a phone call or when the screen is locked. When this happens, the application's suspend methods are called.
Depending on the nature of the event, three different suspend methods might be called.
applicationWillSuspendUnderLock
The iPhone screen is locked either by pressing the power button or during an idle screen lock.
applicationWillSuspendForEventsOnly
Events that force the application into the background, such as receiving a phone call, cause this method to be called. Also, if the display is locked, but no applicationWillSuspendUnderLock method is overridden, this method gets called instead.
applicationSuspend
This method is called when the user presses the home button. It's also the last chance for an application to perform any necessary actions. If neither of the other two methods have been overridden, this method gets called for all suspend events.
Because one method picks up the s