Get $500+ of the best After Effects files, video templates and music for only $20!
Introduction to iPhone SDK Development
basix

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.

Add Comment

Discussion 111 Comments

Comment Page 1 of 21 2
  1. BoltClock says:

    This has got to be the most original introductory iPhone SDK tutorial yet! Fabulous job Mark!

    I do have one question: how do I get the button to scale to fit the view, instead of to the actual size of the cookie images? Right now the images are slightly larger than the portrait width, so they get clipped.

  2. kswiss says:

    ahh nice

  3. Max says:

    Looks interesting! A introduction to Objective-C would be helpful I think.

  4. Looks like it's time to sign up to the developer program, this looks brilliant! Nice work. A decent introudction to the SDK at last!

    :D

  5. An absolutely fantastic introduction. Great work, Mark. Really looking forward to learning more about the technical ins and outs of iPhone development!

  6. Belinda says:

    Wow. I can't wait to learn more about this. I have not even THOUGHT about developing for iPhones (I don't even have one) but it would be a great skill to have. I mainly use a PC but I do have a Mac running OS X 10.5.7 … I guess it's time for an upgrade!!

  7. Wow, this is great, look forward to more of these iPhone Tuts. Thanks!

  8. Saad Bassi says:

    Awesome. Thanks for the tut. Really it will be awesome if you just concentrate on tuts for beginners.:) And then moving to intermediate and then advanced. Thanks a lot for this brilliant tutorial.:)

  9. Juan C. Rois says:

    Congratulations on this new site, It's a great idea and long overdue.

    I know i'd be a coming back here for ideas and knowledge about mobile development, this tutorial is

    a great example of what I've been looking for to get started.

    Thanks and congratulations again.

  10. Joffrey says:

    Great post! Exactly what I needed to start iPhone development. :)

  11. Bruno Crociquia says:

    I was waiting for flash cs5 to build iphone apps.

    But since they hit the flash community with the new cross platform policy i'm glad you have this up.

  12. is there a python API for iPhone SDK ?.

  13. Philo says:

    One of the best iPhone SDK Introduction I've seen on the web! Great tutorial! :)

  14. Kael says:

    So, as I understand this tut is useless for PC users?

  15. Finally a site that touches Objective C. Although we need a proper Objective C tutorial, but it'll be hard to tackle all the hurdles in Objective C in a single tut / screencast.

    Hope to see more soon :)

  16. Adam Webster says:

    I am really excited for these types of tutorials, can't wait for more.

  17. irengba says:

    Well explained. Few weeks ago I was looking for this kind of tutorial. I didn't even find on the iPhone developer site and are hard to understand for biginner like me. Looking forward to more of this stuffs. Thanks

  18. ben smithson says:

    Nice. Keep them coming. I'm still fighting the urge to dive in to development.

  19. Great! This is probably the best introduction to iPhone App'ing I can get. BTW, if you want to screenshot seperate windows just use CMD+SHIFT+4, then press SPACE BAR and you get a little camera icon hover over the window you want and click. It makes thing faster and a lot neater.

  20. Mladjan says:

    Great tutorial.

    But, I have problem with provisioning profile. Can you make some tutorial for making this profiles, how to register on developer program and etc… ?

  21. Eric Granata says:

    Really looking forward to more! Went through the tutorial but upon finishing it, the app I ended up with does nothing when the button is tapped. Any chance at downloading a working project so I can see where I goofed?

  22. DED says:

    This is great, I would like to see these TUTS expand to include iPad development as well. The 3.2 SDK includes an iPad simulator with the iPhone. Great addition to the Tuts family of sites.

  23. David Ferguson says:

    I've been eagerly waiting on this site to launch ever since I first heard about it.

    Can't wait to see what comes up here

  24. Excellent tut, I will try it. I'm a beginner dev with SDK apple. Great explanation and code dude.

  25. Kate Mag says:

    Congrats for new mobile.tutsplus.com. I can't wait to read articles/tutorials on mobile development here. Thanks for the Introduction to iPhone SDK Development. Great post

  26. Austin says:

    Great tutorial, I'm more excited for the Android ones.

  27. Davidmoreen says:

    If you are just getting into Cocoa I would really recommend, finding some tutorials on getting your feet wet with C, and objective-C. It will help you do much to know what the heck "that line" does :)

  28. iosoma says:

    Great tutorial, quite original!

    Will you guys being planning Android development as well?

  29. yusuf says:

    Brilliant intro, very good for someone looking to get into iphone development.

    Can't wait for the Android version ;).

  30. Riftmaster says:

    Is thier going to be an iPhone theme for Tuts+? (I mean a mobile site)?

  31. xun says:

    hmm. i think i should get my ass on this. huhu. I have several ideas, and now i shall be able to code them! woot!

  32. Jaspal Singh says:

    Great tutorials for beginners.

    Can you please post links for "iPhone Simulator for Windows"?

    Thanks.

  33. nestdev says:

    That's great tutorial. we has been bookmarked it. Take look at http://nestdev.com/iphone/introduction-to-iphone-… Thanks :)

  34. Sven says:

    Nice Tutorial,that's exactly what I need to get in touch with xCode. Thank you very much.

  35. Niklas says:

    Splendid! Great tutorial. Thanks a lot!

  36. vLi says:

    Sadly it's only for Mac =( .. would love to develop my own app!

  37. Huy Huynh says:

    As a million iphone user out there, I fell in love with my iPhone right away. I would love to try this tutorial to develop my own app. Thanks for great post, hope to see more coming!

  38. Alex says:

    Hi guys, I was waiting for some iPhone programming tuts and you guys are gret for sharing this. Though how about us, pc users? There's no alternative for us? Thanks

  39. Josh says:

    Great intro to the iPhone SDK can't wait to see some more tuts on building apps just a shame you can't run xCode on linux.

  40. Vasilis says:

    Thanks nice tutorial,it would be great to add some more things in the future…

  41. Elyas says:

    Great Tut Mark, Congrats to TutsPlus for yet another great site!

    Too bad this tutorial can only be done in Mac and not a PC but hopefully I'll get a Mac this summer and be able to tackle this tutorial.

    Looking forward to more tutorials like this; including apps for Blackberry!

  42. Jessica says:

    I must be the only one who ended this tutorial with 16 errors. Stuff like "duplicate interface declaration for class "FortuneViewCrunchController".

    And "No declaration of property 'window' found in the interface", "No declaration of property 'viewController' found in the interface" etc.

    Is there some *completed* downloadable code available so I can compare the finished project to the mess I apparently made with this one?

    Thanks,

    Jess

    • Jessica says:

      Worked through it again today and noticed that I had an issue mapping TouchDown back to FileOwner — that appears to have fixed it and the app compiles and runs now. Thanks so much! Looking forward to working through more tutorials on your site and maybe going Premium to access content on the other tuts sites! :)

  43. Deoxys says:

    Oh, wow, the first tutorial here on mobile tutsplus makes me loving this site. Just wonderful and right on time! I just wanted to explore developing for iphone/ipad. Ah, I'm so happy :)

  44. Andrew says:

    Fantastic! Greatly looking forward to more tutorials like this!

  45. Tim says:

    I had this exact same problem, thanks for posting :D

  46. FLASHY says:

    As a lot of people I was expecting to develop iPhone apps on Flash CS5, but Apple decided to stop the party before it even begun some weeks ago…so thanks for this tutorial.

    I can't believe it doesn't work on Leopard though, and that we need our Snowy friend….kinda sucks…Apple.

  47. Bakari says:

    Looking forward to trying this out. Thanks for posting.

Comment Page 1 of 21 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.