Introduction to iPhone SDK Development

Introduction to iPhone SDK Development

Tutorial Details
  • Technology: iPhone SDK 4
    Difficulty: Beginner
    Estimated Completion Time: 45 Minutes

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.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Mcteapot

    Lol, the images are not loading on the iPad…

    • Ender

      Ha! Serves you right for having an iPad, the single least useful thing to be released since the pet rock.

      • Tom

        Good prediction mate.

      • AussieGuy

        lol so confident yet so wrong.

        prediction FAIL

        btw – great tutorial!! couldn’t have been any easier to follow :)

  • Rogério Toled

    Great tutorial Mark! Hope to see more tutorials.

  • http://kennedykong.com Kennedy

    THIS IS FANTASTIC!!!!

  • http://www.theslurps.com annie

    Great, thx !

  • Rick

    Can I get this as a memory implant? That's what I really need.

  • http://www.scottydewar.com Scottyd

    Thanks for the Tut, it was fun to go through.

  • http://www.churchcreative.net Angel

    i keep getting an error on the last part after adding the code in the FortuneCrunchViewController.m file

    this is the error message i get "previous definition of '-[FortuneCrunchViewController dealloc]' was here

    • http://mobile.tutsplus.com Mark Hammonds
      Author

      Hey Angel, the basic iPhone template you created already had a "-(void)dealloc" method in the .m file, so it sounds like you pasted in the code above without removing the old version, thus duplicating the method in your code. You need to either remove the original, template version of dealloc or just insert the new lines above into the original dealloc method. Hopefully this helps!

  • http://3dimentional.blogspot.com Cesar Mujica Castro

    Just what I was looking for.

  • http://www.funwithiphone.com Chris

    I went through the tutorial, (very nice tutorial, BTW, easy to follow,) everything works fine on the iPhone Simulator, but when I install it on my iPhone, the unbroken cookie appears OK, but when I touch the cookie, only the fortune label appears, the broken cookie pic doesn't appear. Any ideas?

    Thanks again for a great tutorial, I'm looking forward to more!

  • http://n/a gaf

    i was hoping this would be the next step for the tuts+ network

    cant wait to see some more tuts.

    cheers!

  • MWUK

    Great tut!

    I look forward to diving into this over the summer (along with http://developer.apple.com/iphone/library/documen… however I was wondering whether mobile tuts+ would post a comparison between the multiple mobile platforms?

    It could include sections such as: ease-of-use for different levels; piracy risk (and if its possible to prevent it); cost; estimated users for each platform; as well as how restrictive/censored an application could be even if it was socially acceptable…

  • http://www.blackcherrydesign.com Zoe Francis

    Thnx for this! Will be using it to create my first ever iphone app!

  • http://reconnectstrategies.blogspot.com Tisha Major

    If only I had a quarter for each time I came to mobile.tutsplus.com… Great article.

  • begs

    Very nice one. Thank you for this. Everything was clearly understandable and functional in my first try.

  • Mike

    Having some trouble with step 4 with “linking” the Button with the actual button in the interface designer.
    Dragging a line on the label works just fine, but I can’t seem to grab the UIbotton by draging a line from the circle to the image, tried manu different positions on the image…

    Any advice?

  • http://www.yourdesignblog.co.uk Szabi

    Beginning of step 4 is completely missing for me. I did update the .h file with all what you said then went back to the interface builder and I can not connect the objects and cookie crunch action to anything as the File’s Owner is empty. There is only the view connected to view there.

    What can be the problem?

  • http://www.yourdesignblog.co.uk Szabi

    I solved it. :) Sorry. I copied the example but did not change the project name to mine. Oooops. Step 5.

  • David

    seriously fantastic work, thank you so much for this tutorial. That is why I pay for a membership.

    I definitely want to see more of these, including bindings and KVO’s!

  • Matt

    Hey Mark I'm trying to do this tutorial but I'm having a problem launching the interface builder. I'm running snow leopard 10.6.4 and in the top left hand corner of xcode it says simulator-4.0. Any help that you can provide will be greatly appreciated.

  • Aqasa

    firstly thanks for the tutorial. however i got an error saying redifinition of ‘-[FortuneCrunchViewController dealloc]‘ regarding – (void) dealloc {

    any advice?

  • http://www.dangermoose.co.uk flashmac

    Great, I’ve followed the tut from start to finish and now I have my first app!

    A very well documented and paced tut for first timers like me. Thanks v much.

  • http://www.twitter.com/ubermatik Theo Hodkin

    Could someone help me please? I'm getting the message "/Users/theohodkin/Documents/Test/Classes/TestViewController.m:13:0 /Users/theohodkin/Documents/Test/Classes/TestViewController.m:13: error: no declaration of property 'fortuneCookieButton' found in the interface

    /Users/theohodkin/Documents/Test/Classes/TestViewController.m:17:0 /Users/theohodkin/Documents/Test/Classes/TestViewController.m:17: error: 'fortuneCookieButton' undeclared (first use in this function)

    /Users/theohodkin/Documents/Test/Classes/TestViewController.m:19:0 /Users/theohodkin/Documents/Test/Classes/TestViewController.m:19: error: 'fortuneLabel' undeclared (first use in this function)

    /Users/theohodkin/Documents/Test/Classes/TestViewController.m:69:0 /Users/theohodkin/Documents/Test/Classes/TestViewController.m:69: error: 'fortuneCookieButton' undeclared (first use in this function)

    /Users/theohodkin/Documents/Test/Classes/TestViewController.m:70:0 /Users/theohodkin/Documents/Test/Classes/TestViewController.m:70: error: 'fortuneLabel' undeclared (first use in this function)"

    Sorry for the long post, but I'm a beginner at all this. Thanks.

  • http://www.twitter.com/ubermatik Theo Hodkin

    It's okay, fixed now… but I still have a problem – when my app opens in the Simulator, it closes straight away. Any ideas?

  • http://brainflood.tumblr.com/ daniel

    works fine, however when i close and reopen the app in the simulator (i.e. hitting home button then reopening) the cookie isn’t reset and it’s still the broken image. how would we reset it so it goes back to being unbroken? thanks for the great tut!

  • http://cendhika.com cendhika

    this is the answer of my question “where should I start?”

  • Lee

    Newbie mistake…I saved my changes in Xcode, but I assumed it was saved for Interface Builder. Obviously, it wasn’t working.

    Anyway, saved changed in Interface Builder and it works now!! Great tut!

  • Earle

    I tried this FortuneCrunch tutorial and have a few problems.

    First when I control click File’s Owner the connections are not there. I searched and found them in the MainWindow.xib’s FortuneCrunchAppDelegate instead. Next, I cannot connect them to the button or label in the FortuneCrunchViewController’s View. This is a common problem with all of my attempts to do any examples or tutorials. Can anyone identify my problem? I am using Interface Builder 3.2.5 (823). Maybe I just have a corrupted tool or the sequence of events has changed significantly with the new tools?
    HELP!

    • Earle

      Well it seems that I have finger trouble. Once I put the code in the right place (blush) I watched a Stanford University video and it seems SDK4 must also connect differently than SDK3. Now I can proceed to my next problem(s).

  • lifeShadows

    its impossible to produce iphone application in windows OS laptop?

  • Chris

    Not sure if this has been updated yet. But it would be great if they could update it for Xcode 4. It shouldn’t be too difficult, easy to figure out either way, and very helpful. Thanks.

  • Sergio

    Hello,

    I have xcode 4 and when open a new project I don’t see Classes, other sources and sources folders, only show me frameworks, products and name project folders. Why?.

    Thank you.

  • Dan

    I get an error on building that says “Type of property ‘fortuneLabel’ does not match type of ivar ‘fortuneLabel’. I know it is something small I’m missing. Yes… I’m a newbie. Where’s my mistake oh Great Ones?

  • http://www.lucasdelrio.com.ar Lucas del Río

    This question might sound silly, but indeed I need to know. Is it possible to develop this on Windows 7? I don’t have a Mac unfortunately but I really want to learn this stuff and try it on my own. I’ve got an Iphone 4S to test this but not a Mac to develop it…

    • Emily

      From my understanding, you must have a Mac to develop an iOS application.

  • lash

    i need iphone simulator for windows.

    • Linish

      Use phone gap or sencha touch

  • Linish

    Great starting tutorial :)