Channels ▼


The iPhone Isn't Easy

Variations on C

The iPhone runs a stripped-down version of Mac OS X and uses a subset of the Cocoa application frameworks, along with some new ones, to support its touch interface. These revised frameworks are known as Cocoa Touch and comprise the iPhone platform's APIs. (For further information on the iPhone platform, see Smartphone Operating Systems: A Developer's Perspective. OS X programmers will have an advantage here in that they are familiar with the programming language and frameworks. There are some differences between the frameworks, however. For example, the primary Cocoa framework for OS X is AppKit, while on the iPhone the primary Cocoa Touch framework is UIKit. UIKit, as its name implies, consists of lightweight UI classes tailored for the resource constraints of a hand-held device. Also, the keyboard and mouse interfaces are absent. I'll point out more differences between the two platforms as I go.

Again, you write an iPhone with Objective-C. Objective-C consists of extensions to the C that implement many OOP techniques, such as object encapsulation, inheritance, and polymorphism. Because the language is a superset of C, Apple's Objective-C compiler accepts C and C++ source, which makes it ideal for reusing existing code written those languages. In fact, some games ported to the iPhone consist mostly of C code, and Objective-C code is used only to interface with the Cocoa Touch frameworks. For example, id Software's Wolfenstein 3D takes this route, since its core logic was written in C. John Carmack, the game's creator, was able to write Objective-C wrapper code that communicated with the iPhone's APIs, while the complex pieces of the game, such as the game's raycasting logic and its rendering engine, were left intact. Carmack has made the source code of Wolfenstein 3D available for download from the id Software web site.

Objective-C has its own language idiosyncrasies for defining objects and implementing other OOP-based design patterns. How you invoke methods differs, for example. In Objective-C, you don't "call" a method, rather you send a "message" to the object that owns the method, like so:

[shipView upDateShip:kNoThrust];

The content within the square brackets contains the gist of the message. To wit, this message is directed to the shipView object, and invokes its upDateShip method, while supplying it with an argument that consists of the constant value kNoThrust.

Another important difference is that for certain complex UIKit classes you don't extend their behavior by subclassing them and writing override methods. Instead, you edit the supplied "delegate" class that implements the desired behavior. For example, you do not extend the UIApplication class that implements the core application functions. You modify and add overrides to a UIApplicationDelegate class. Messages unknown to the UIApplication object are routed to your UIApplicationDelegate object, where your custom methods can respond to them. You can get detailed information on Objective-C from the Objective-C 2.0 Programming Language manual, and more information on UIKit and message passing from the iPhone Application Programming Guide. Both of these documents are available on the Apple iPhone developer site.

Given all of the changes implemented by Objective-C and UIKit, the structure of an iPhone app is an interesting mixture of the old and new. When the iPhone OS launches an app, it calls the standard C function, main() (Listing One). However, all that main() does is set up a memory pool for your app and optionally parses any argc and argv arguments.

Listing One

#import <UIKit/UIKit.h>

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;

However, here the resemblance to C ends: main() immediately calls UIApplicationMain() function, which generates an instance of the UIApplication class. It also creates your delegate object, which is your modified UIApplicationDelegate class. UIApplication then starts receiving events from the iPhone OS and sends them to your delegate. For example, when your delegate receives an applicationDidFinishLaunching message, this signals that the app's runtime environment is established and running. You respond to this message by executing the delegate's applicationDidFinishLaunching method, which contains custom initialization code, and creates any required objects. (Listing Two).

Listing Two

#import "SpaceAppDelegate.h"
#import "SpaceViewController.h"

@implementation SpaceAppDelegate
@synthesize window;
@synthesize spaceViewController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
	application.statusBarHidden = YES;

// Make instance of our controller
	SpaceViewController *aViewController = [[SpaceViewController alloc] 
                    initWithNibName:@"SpaceView" bundle:[NSBundle mainBundle]]; 
	self.spaceViewController = aViewController; 
	[aViewController release];
// Restore state if necessary
	[spaceViewController restoreState]; 
// Add view managed by controller to main window
	[window addSubview:spaceViewController.view];
    [window makeKeyAndVisible];
// Application will be terminated soon, save state data
- (void)applicationWillTerminate:(UIApplication *)application {
	[spaceViewController setMode:PAUSE];
	[spaceViewController saveState]; 
// Release all objects
- (void)dealloc {
	[spaceViewController release];
    [window release];
    [super dealloc];


Another difference from C is that the iPhone APIs don't provide a method that allows you to terminate an application. Instead, your app receives an applicationWillTerminate message, which signal that the iPhone OS is preparing to shut the app down. In response to this event, your delegate executes an optional applicationWillTerminate method that saves the app's data context (if required) and tears down any storage that it set up in applicationDidFinishLaunching. This routine should execute quickly, as the iPhone OS usually terminates the app within a few seconds.

Now that I had a grasp of Objective-C and an idea how the iPhone OS interacted with an app, my next step was to figure out how to draw something onto the device's screen. That meant delving further into the frameworks.

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags


<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags


<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

