Advertisement

Introduction to iPhone SDK Development

by

Mobiletuts+ will be covering all major mobile platforms – iPhone, Windows, Android and Blackberry. This tutorial looks at development with the iPhone SDK. You will learn information about the iPhone platform, how to setup and configure your development environment, and the steps necessary to create a simple fortune cookie application!

About the Platform

iOS is a mobile optimized variant of Mac OS X created by Apple Inc. It is distributed with all iPod touch, iPhone, and iPad devices, and only occupies about 500 MB of storage space.

There are three distinct approaches to iOS development:

  1. Web Application Development

    The original iPhone OS 1.0 required all non-Apple applications to be web-based and executed within the Mobile Safari web browser. Because Mobile Safari does not support plugins like Adobe Flash or Microsoft Silverlight, this meant that all third party applications were originally written in HTML, CSS, and JavaScript. This method of development remains a viable option today, especially for applications that must be accessible on a wide range of devices or for development teams with an aversion to Mac OS X and Objective-C.

  2. Native Application Development

    With the release of iPhone OS 2.0 and the introduction of the iPhone SDK and iTunes App Store, developers have been encouraged to write native applications for the iPhone using Objective-C and Xcode. Native applications are compiled binaries that are installed and executed on the user’s device. These applications are granted considerable access to the device hardware, and only native application binaries can be distributed through the iTunes App Store. Because the iPhone OS runs on iPod touch, iPhone, and iPad devices, most applications can be built for all three devices with only minor code variations, though there are significant advantages to optimizing your application for the much larger iPad screen.

  3. Hybrid Application Development

    It is also possible to combine the above approaches and create iPhone applications that are installed on a user’s device, are written primarily in HTML, CSS, and JavaScript, and are released through the iTunes App Store. Such applications are growing in popularity thanks to open-source libraries like QuickConnect and platforms like PhoneGap, AppCelerator, and rhomobile.

Mobiletuts+ will cover all of the above methods of iPhone OS development, but this tutorial will focus on native application development with the official iPhone SDK using Objective-C and Xcode. This is Apple’s recommended method of building native iPhone OS applications for distribution in the iTunes App Store.

Getting Started

In order to develop iPhone SDK applications and continue this tutorial, you will need the following:

  • An Intel-based Mac running Mac OS X Snow Leopard

    In order to write native applications with the official iOS SDK and test your applications in Apple's official iPhone or iPad Simulator, you will need to be able to run Snow Leopard, the latest desktop and laptop operating system from Apple.

  • An Apple Developer account.

    This is required to download the iPhone SDK 4, the Xcode IDE, and the iPhone Simulator. You will need to register for an Apple Developer account here. Registration is free and will allow you to run applications in the iPhone simulator. A free account is all that is needed for this tutorial, but to actually run your apps on a device or publish through the iTunes App Store you will need to pay to enroll in the iPhone Developer Program.

  • Xcode and the iPhone SDK 4.

    After logging into your developer account, download and install Xcode 3.2.5 and iPhone SDK 4 (or the latest available versions).

After you have the above, you should be ready to dive into building “Fortune Crunch,” a simple iPhone application that will allow users to “crunch” a fortune cookie and read a message.

Step 1. Launch Xcode and Create Your Project

Xcode is an integrated development environment (IDE) that combines the multiple tools necessary to build an iPhone program into one application. Launch Xcode now by searching for it in spotlight or using finder to navigate to the default install path of /Developer/Applications/Xcode.

Select “Create a new Xcode project” from the dialogue box that appears.

Creating an iPhone SDK Project

Select “Application” under iOS in the left column. Familiarize yourself with the various types of application templates available in the content panel. This tutorial will be a simple, single view app, so select the “View-based Application” icon and click “Choose.”

Selecting View-Based application tempalte

Enter the text “FortuneCrunch” into the “Save As” field to name our project and click “Save.”

Entering iPhone project name

The FortuneCrunch project template should now be displayed on screen.

The FortuneCrunch project template

It is important to realize that this starting point is a fully executable program. Go ahead and use the iPhone simulator to run the template by clicking “Build and Run” or by selecting Build > Build and Run from the menu bar.

Project template in the simulator

Though the default application template is incredibly drab, the iPhone simulator is not. Click the home button in the simulator to return to the iPhone dock and browse around a bit. Also note the following simulator short cuts:

Command + left arrow: Rotate the device left.

Command + right arrow: Rotate the device right.

Ctrl + Command + Z: Emulates a shake gesture (this will not display visually).

Step 2. Launch Interface Builder and Create the Interface

The default interface provided with a View-based template is incredibly boring, so let’s continue by creating our fortune cookie app UI. We will use two fortune cookie images that were taken specifically for this tutorial: cookie-closed.png and cookie-crunched.png. You can find them in the download file attached to this post, and they are freely distributed under the WTFPL license.

After obtaining the necessary fortune cookie images, launch Interface Builder by going to the “Groups & Files” pane in Xcode, expanding the “Resources” folder, and double clicking the FortuneCrunchViewController.xib file.

Selecting FortuneCrunchViewController.xib

Interface Builder is a graphical tool that allows you to quickly and easily create the layout of your application without writing a single line of Objective-C code. As we will see, it also allows you to visually define relationships between objects like buttons and the methods that you write in your application.

Interface Builder Screen

There are four main Interface Builder windows that you need to know about:

  1. The XIB Window. This window is titled “FortuneCrunchViewController.xib” and is a representation of everything that is stored in the XIB file you double-clicked to open Interface Builder. File’s Owner represents an instance of the FortuneCrunchViewController class. You can think of the View in the XIB window as the canvas for your single-viewed application, and First Responder is a placeholder for an object determined at run time that will respond to actions like touch events.
  2. The View Instance. The view instance is essentially your canvas for this application, and should look familiar from running the template app in Step 1. Changes that you make here will be reflected when we build and run the application. If the view instance isn’t open or if you want to open it again after closing it, you can do so by double-clicking the “View” icon in the XIB window.
  3. The Library. The library displays objects like buttons, labels, and text fields that are available for use in your view. Objects can be created in your canvas simply by dragging them onto the view instance. To manually open the library, select Tools > Library from the menu bar.
  4. The Inspector. The inspector provides a detailed view of the attributes and connections of your objects. Open the inspector window by selecting Tools > Inspector if it isn’t already open. Note the four tabs at the top of the inspector window: attributes, connections, size, and identity.

Now that you are acquainted with Interface Builder, we can continue to setup our application’s interface.

First, let’s change the background color from gray to white. Do this by selecting the View Instance described above. The inspector window should now have the view properties loaded. Select the attributes tab in the inspector, locate the background attribute and color palette, and change the color to white.

Changing View Background Color

Now, we are going to create a button to represent our fortune cookie. In the library window, type “UIButton” into the search box at the bottom.

Searching for UIButton

Next, drag the button onto the view instance.

Dragging the UIButton onto the canvas

We need to add the cookie-closed.png and cookie-crunched.png images to the resources folder in Xcode. Switch back to the main Xcode window and drag each image into the Resources folder in the Groups & Files pane. A dialogue box will appear. Check the box that reads “Copy items into destination group’s folder” and click “Add.”

Adding Fortune Cookie Images to resource folder

Switch back to Interface Builder and select the UIButton added earlier. Use the inspector attributes tab to change the image property to cookie-crunched.png and the image type to “custom.” Resize the UIButton to the size of the image by selecting Layout > Size to Fit.

Broken Fortune Cookie Placeholder

We now have a broken fortune cookie on screen. Let’s create our fortune by dragging a UILabel from the library to the view. Change the text to read “Happy iPhone Hacking” and use the inspector attributes tab to change the font to 12 point size and the typeface to bold. Size the UILabel to fit the text, and position it over the white paper slip on top of the broken cookie image. Now select the “Hidden” checkbox as we only want this label to display after the user has tapped the button.

Positioning fortune label on screen

Select the UIButton again, and change the image setting in the inspector attributes tab to cookie-closed.png.

Fortune Cookie Uncrunched

Be sure to save all your work in Interface Builder, and then switch back to Xcode and build and run your application again. You should now see the unbroken fortune cookie button on screen.

Fortune Cookie In iPhone Simulator

Step 3. Code the FortuneCrunchViewController Header File

With the interface configured, we are ready to dive into Objective-C and begin writing the code that will make our application function.

Back in Xcode, select the FortuneCrunchViewController.h file under the Classes folder in the Groups & Files pane. This file is what is known as a “header,” "interface," or “declaration” file for the FortuneCrunchViewController class. It is where we declare the internal variables, methods, protocols, and other components that will be used in the class.

The FortuneCrunchViewController class was visually represented in Interface Builder as the “canvas” that we were able to drag the UILabel and UIButton instances onto. We are now going to update the class header file so we can reference these objects later in our code.

Update the header file by making the following changes:

#import <UIKit/UIKit.h>

@interface FortuneCrunchViewController : UIViewController {

	IBOutlet UIButton *fortuneCookieButton;
	IBOutlet UILabel  *fortuneLabel;
	
}

@property(nonatomic, retain) IBOutlet UIButton *fortuneCookieButton;
@property(nonatomic, retain) IBOutlet UILabel *fortuneLabel; 

-(IBAction)crunchCookie:(id)sender; 

@end

Line 1 is known as a preprocessor directive, and is essentially telling the preprocessor to make the UIKit framework available for use within the class.

Line 3 uses @interface to declare that this is an interface definition for the FortuneCrunchViewController class. The ": UIViewController" portion of this line means that FortuneCrunchViewController is a child class of the UIViewController class.

Line 5 declares a UIButton class pointer called fortuneCookieButton as an IBOutlet. The IBOutlet tag has no real meaning to the compiler, and is only used by Interface Builder to determine what objects in the class can be connected to their visual representation in the Interface Builder XIB file. The UIButton class should be familiar from our work in step 2.

Line 6, similar to line 5, declares a UILabel class pointer called fortuneLabel as an IBOutlet.

Lines 10-11 use the @property statement to tell the compiler that fortuneCookieButton and fortuneLabel will be accessible as properties of the class, but that we will declare the methods to access them dynamically later.

Line 13 is a function signature for the crunchCookie method. The -(IBAction) portion of the statement declares this method to be of the IBAction data type, which is essentially the same as of the void data type, with the only notable difference being that IBAction makes this method accessible as an action in Interface Builder. The “:(id)sender” portion of the statement tells the compiler to accept an argument called "sender" of the "id" data type. In Cocoa-Touch, id is a generic data type that can be a pointer reference to any subclass of NSObject, and in our application calling the crunchCookie method by pressing the fortuneCookieButton will actually send a reference to the fortuneCookieButton as the “sender” object. This isn't necessary for our application, but it is included here because it is a common convention that you will see often.

Finally, line 15 indicates that this is the end of our @interface declaration.

Step 4. Connect Interface Builder to FortuneCrunchViewController

Now that we have declared the internal variables and methods that will be used by our application and tagged them with IBOutlet and IBAction, we need to complete the circle by connecting our Interface Builder objects to the FortuneCrunchViewController class.

Double-click the FortuneCrunchViewController.xib file and launch Interface Builder again.

Right click or control click the File’s Owner object in the XIB controller. A box will appear that lists the various objects in the File’s Owner that can be connected to objects in the XIB. Notice that the “view” is already connected for us.

Viewing File's Owner Outlets

Click the circle to the right of fortuneCookieButton and drag from the File’s Owner box to the actual UIButton on the canvas. The File’s Owner box should be graphically updated to display the connection between the fortuneCookieButton and the UIButton object in the same way that it indicates the connection between the view outlet and View object.

Connecting fortuneCookieButton

Now do the same for the fortuneLabel connection.

Connecting fortuneLabel outlet

We now need to establish a connection between the UIButton and our crunchCookie method. Interface Builder provides us with many different ways to do this. Control click or right click on our fortune cookie button to display a list of available events.

fortuneCookieButton action outlets

Two of the most commonly used options include:

  • Touch Down. This option tells Interface Builder to fire our method when it detects a finger “touch down” on the element.
  • Touch Up Inside.This option tells Interface Builder to fire our method after the user has both touched a finger down on the element and subsequently released the finger from the element as well.

Touch Up Inside is usually the option chosen when working with buttons, but in our case, we want the fortune cookie to break the moment the user’s finger touches it, so we will bind the Touch Down event to our crunchCookie method. Do this by dragging from the circle to the File’s Owner object in the XIB window, and then be sure to select the crunchCookie method from the dialogue box that pops up.

Connecting touchDown

Save your work in Interface Builder and then switch back to Xcode.

Step 5. Code the FortuneCrunchViewController Implementation File

With the Interface Builder XIB file configured and our class interface written, all that remains is to code the class methods that the application will use to crunch our cookie and display the fortune label. The class implementation file is FortuneCrunchViewController.m, open it now by selecting it from the Classes folder in the Groups & Files pane.

Update the code to the following:

#import "FortuneCrunchViewController.h"

@implementation FortuneCrunchViewController

@synthesize fortuneCookieButton;
@synthesize fortuneLabel;

// This method changes the cookie image when the button is pressed:

-(IBAction)crunchCookie:(id)sender {
    NSLog(@"In crunchCookie");
    [fortuneCookieButton setImage:[UIImage imageNamed:@"cookie-crunched.png"]
                         forState:UIControlStateNormal];
	
    fortuneLabel.hidden = NO;	
}

// These methods are related to memory management:

- (void)viewDidUnload {
    [fortuneCookieButton release];
    fortuneCookieButton = nil;
}

-(void)dealloc {
    [fortuneCookieButton release];
    [fortuneLabel release];
    [super dealloc];
}

@end

Line 1 is the preprocessor directive to include the interface file prior to compiling the class.

Line 3 begins our class implementation.

Lines 5 - 6 use the @synthesize statement to dynamically create methods for accessing and saving the fortuneCookieButton and fortuneLabel pointer objects we declared in the header file. This step removes the need to hand code getVariable() and setVariable() methods for all the objects we declare.

The crunchCookie method is found on lines 8 - 12, and is the heart of this program.

On line 9 - 10 we create a new UIImage object using the cookie-crunched.png image. We then pass this object into the setImage: forState: method of the fortuneCookieButton object. This method will change the image attribute we manually set to cookie-closed.png in Interface Builder to the new UIImage object that we passed in. Message passing is a central component of the Objective-C language, and generally follows this pattern:

[myObject methodParam1:value1 methodParam2:value2]; 

Line 11 accesses the attribute “hidden” of the fortuneLabel object, and sets its value to NO. This will reveal our label object after the image updates to the crunched cookie.

All remaining lines deal with memory management issues that will be covered in greater depth in future tutorials. To summarize though, when our view unloads, you need to be sure that you have released any IBOutlet objects that you have created. As for the dealloc method, this is the object destructor and is called when the object is about to be destroyed. Both of these methods already exist in the class by default, but you will need to add the lines shown to them.

With the above code in place, we are ready to save, compile, and run our finished application!

Final Fortune Cookie In iPhone Simulator

Conclusion

This tutorial has provided you with a brief introduction to native iPhone OS application development with Xcode, Interface Builder, and the iPhone SDK. We covered some of the basics of the platform and you got your feet wet with Interface Builder and Xcode.

The material covered in this tutorial will be expanded upon in future tutorials as we dive further into Objective-C, Cocoa-Touch, and the iPhone SDK.

Advertisement