On January 9, 2007, at 9:42 a.m., the world changed forever. Something
special was introduced to us, but not all of us knew just how
special it would become in such a small amount of time.
The product we know as the iPhone is more than a gadget. It is a
phenomenon. Many of us know news headlines, stock trends, and our
day’s schedule before we even get out of bed. And thanks to the iPhone
SDK, there are more than 50,000 other things we can do, wherever and
whenever we want. It truly is “your life in your pocket.”
When I joined Apple in 2001, there was no App Store, no iPhone, and
no iPod. Mac OS X was just a few weeks old. It is amazing to think how
far things have come. The iPhone has created its own economy, where
you no longer need patents or institutional investment to be wildly successful.
All you need is an idea and the motivation to realize it.
As an iPhone developer, not only will you be participating in this phenomenon,
but you will join a family of passionate, brilliant engineers,
designers, and marketers who take more pride in their work than most
of the people you’ve met. In many cases, their dedication dates back
to the early releases of Mac OS X, and even the Classic Mac OS. They
make conferences feel like reunions. They share knowledge with “competitors”
because they know that better apps—whoever they’re from—
make a better platform. They love this technology. They live on it. They
have built their careers on it. Working closely with them for more than
eight years inspired me to leave my dream job and join their ranks.
This combination of technology and community has produced the historic
times we now live in. Just one year after the App Store was born,
it’s hard to remember life before it, and yet there is surely so much
more to come.
FOREWORD 14
The platform is still growing, and we are all still learning. Your efforts
will contribute to that story as it continues to unfold. This book is your
first step in that special journey.
Welcome to our world. You’re going to love it.
Matt Drance
July 11, 2009
Sent from my iPhone
Chapter 1
Introduction
The iPhone has changed everything.
Maybe by the time you read this you’ll no longer notice that the latest
cool new phone from every manufacturer looks and behaves more
like the iPhone than like the models they used to sell before the iPhone
was released. Meanwhile, at the time we write this, Apple’s iPhone ads
showcase the apps that you and other third-party developers are creating.
The Apple marketing campaign is highlighting the iPhone as a
platform for great software—software that you will create.
It’s hard to overstate just how much the iPhone SDK and the App Store
have changed the way we develop, release, and consume mobile software,
even in the short time that they’ve been available.
Before the iPhone, writing software for the small device was rife with
hazards. Many developers complained of fragmentation, the way that
different devices would have different characteristics (screen sizes,
color depths, input technologies, and so on) and different implementations
of supposedly standard technologies, whose variant behaviors
forced developers into an expensive and difficult game of “write once,
test everywhere.” And that’s only in the cases where they had access to
a market; in some cases, handset makers and mobile telephony carriers
used the technology vendors’ security practices as a means of enforcing
business models, allowing only first-party applications on the device or
crippling third-party apps by denying essential services, such as access
to the network. It was enough to send developers fleeing back to the
desktop, if not the server.
CHAPTER 1. INTRODUCTION 16
As an iPhone SDK developer, you don’t need to worry about fragmentation.
The iPhone and iPod touch are highly predictable, with only
a few models thus far and highly consistent features and behavior
between them. The SDK brings the tools and technologies of Mac OS
X—refined by years of use creating world-class desktop applications—
and makes its essential elements available for creating iPhone and iPod
touch applications. While other mobile platforms throw an exception if
you touch the networking stack, the iPhone gives you exceptional technologies
such as the self-networking Bonjour. On other devices, playing
a sound file is a hit-or-miss affair, while the iPhone offers extraordinarily
deep support for media. And when you’ve finished writing your application,
instead of a carrier demanding that you “partner” with them
(and give them 99 cents of every dollar you make) and instead of being
shut out entirely if you’re not a big company touting a well-known intellectual
property, the App Store lets you put your application before
every iPhone and iPod touch user. And you set your own price with
Apple taking a much smaller and quite reasonable cut.
The result has been revolutionary. At the rate the App Store is growing,
there’s no point quoting numbers because they’ll be completely out-ofdate
by the time you read this book. Instead, it might be more helpful
to notice the sea change in the industry that has resulted from the
one-two punch of the SDK and the App Store. Carriers that had locked
down their networks are now racing to open app stores of their own,
terrified that every cool new app for the iPhone potentially lures away
more of their customers. Some mobile developers are going iPhone-only.
Given the realization that with iPhone users far more likely to download
and pay for applications, it’s a sucker’s bet to work through the
miseries of other mobile platforms—the aforementioned fragmentation
and obstructionist carriers—in the hopes of reaching a user base that
doesn’t download third-party apps anyway. And in the enterprise, companies
are writing their own custom iPhone applications and deploying
them en masse in the field.
If you’re reading this book, chances are you’d like to get in on this
mobile revolution.
And we’re glad you do, because we’re eager to help see you through the
journey that will take you from downloading the SDK to releasing your
first application.
IN THIS BOOK 17
We begin by assuming only two things:
• You have a computer capable of running the current iPhone SDK.
As of this writing, that means a Mac with an Intel CPU, running
Mac OS X Leopard 10.5.4 or later.1
• You are familiar with a “curly brace” programming language (C,
C++, C#, Java, Ruby, etc.) and with object-oriented programming
in general. If you’re primarily familiar with scripting languages
(JavaScript, ActionScript, PHP), then you may find some of the
iPhone’s programming practices challenging, but we hope not
insurmountable.
1.1 In This Book
We begin your journey with an introduction to the platform. We start
with a quick success in the form of a Hello World iPhone application.
Fresh on the heels of your first success, we dive into some of the fundamentals
of the platform that you will need going forward. We cover the
basics of the tools (Xcode, Interface Builder) and Objective-C, which is
the language of Cocoa Touch development.
In the next four chapters, we look at view controllers and the views that
are integral to most iPhone applications. You’ll begin with a look at the
most generic views and view controllers and move to the UI metaphors
that are key to almost any iPhone application: tab bars, navigation, and
table views.
We recommend that you read these chapters no matter what sort of
iPhone application you are planning on building. You can then work
through the rest of the book in order, or you can pick and choose
according to your needs. We’ve grouped the remaining chapters into
roughly six sections.
If you need to persist data to your device, you’ll find four chapters
that cover the various techniques. We start with filesystem access and
options for saving and retrieving user preferences. Then we show two
approaches to using the built-in database: directly, with the SQLite API,
1. SDK requirements, particularly the minimum OS version, are highly likely to change
going forward. Check http://developer.apple.com/iphone for the current specs.
IN THIS BOOK 18
or via the object-relational mapping power of the Core Data framework
added in iPhone OS 3.0.
Your application may require communication with servers or other devices,
so the next two chapters take you out to the network. The first
connects to websites, web services, and email on the public Internet,
while the second uses the self-networking abilities of Bonjour and the
new-in-3.0 Game Kit framework to connect iPhone OS devices to one
another.
The next section consists of four chapters on interacting with media on
your device. We start with the simple framework for viewing video on
the iPhone and then look at 3.0’s new framework for interacting with
the user’s iPod music library. For developers who want to exploit the
platform’s audio capabilities, we have a chapter on playing and recording
audio with 3.0’s new AVFoundation framework, closing the section
with an overview of the lower-level Core Audio framework.
You are probably going to want to customize the way your users interact
with your application. We return to presentation with a look at events,
Multi-Touch, and gestures. Custom drawing via custom views is the
topic of discussion in the next three chapters. We discuss drawing content
in custom and unique ways with the sophisticated Core Graphics
library, as well as manipulating and drawing images, both those provided
by your application as well as those from the user’s image library.
This section closes with a chapter on Core Animation, the technology
that underlies all the beautiful and natural-feeling animations that you
see throughout the iPhone UI.
Next, we cover the more specialized technologies that not every iPhone
application will use but that, when used properly, really make your
application stand out. Some developers will be interested in using the
built-in accelerometer to sense the device’s orientation and motion,
allowing the user to control applications in new and interesting ways.
Developers of productivity and social networking applications will be
able to use the Address Book framework to interact with a user’s contact
database. And because the iPhone and iPod touch are devices on
the move, we have two chapters on location: one on the Core Location
framework that helps determine the device’s location and a second on
the new-in-3.0 Map Kit framework that lets you present map data in
your application.
ACKNOWLEDGMENTS 19
Our final section offers four chapters on the final steps you’ll need to
take to complete your application. A handful of “application integration”
APIs allow your application to launch other apps and to be launched by
others. You’ll learn to perfect your application with chapters on debugging
your code and improving its performance with Xcode’s various
tools. A final chapter puts it all together by helping you hone your development
process, get your work onto the App Store, and promote it to
the app-shopping public.
1.2 Acknowledgments
From Chris Adamson
When I was part of an office-emptying mass layoff in 2001, I swore
that I was done with mobile application development. A few years later,
crawling to the finish of my second book, I said I’d never write another
one. So, to be writing an introduction to a book on iPhone development,
it would seem I’ve got some explaining to do.
It really all comes down to one moment in March 2008. I was at a
Java conference, skeptically following the web coverage of the iPhone
SDK announcement. Few people, myself included, thought we’d get a
substantial level of functionality in the SDK and were shocked when
what was unveiled was most of Mac OS X’s Cocoa, with the UI rethought
for a touch-based handheld. While I’d never been able to get out to the
network with carrier-crippled Java phones, the SDK offered freakin’
BSD sockets and self-networking with Bonjour as a bonus. Media, often
presented at a toy level of functionality on other platforms, was present
in the form of Core Audio, the same code used by professional audio
applications on the Mac.
And this was all for a phone? I was hooked. I call it my “All Along
the Watchtower” moment: I immediately knew that everything I’d been
doing for years was instantly rendered irrelevant and that this is what
I wanted—needed—to be doing going forward. I got the SDK over a very
slow DSL connection that night, coded my first Hello World on the flight
home, and was recruited for this book a few months later.
Of course, I have to thank our editor Daniel Steinberg for reaching out
to me and convincing me that I was a good choice to coauthor the book.
He’s kept this enormous project on track through months of writing
and rewriting, a shutdown when we feared Apple’s nondisclosure agreement
might keep us from ever releasing it, and the first slam-it-together
ACKNOWLEDGMENTS 20
beta release when the NDA dropped. Prags Andy and Dave also deserve
kudos for a very productive (and yes, I’ll say it, agile) system for book
writing. Bill has been a responsive and productive coauthor, someone
whose strengths are a well-suited balance to my weaknesses. Both of
us are grateful to our many technical reviewers and the huge community
that has developed on http://pragprog.com/, in the book’s forum and
errata page, giving us tons of useful feedback. And thanks as always to
my family (Kelly, Keagan, and Quinn), who somehow withstood the collateral
damage and stress of not only this book-writing marathon but
also a cross-country move just a couple weeks before beta 1.
Obligatory end-of-book tune check: this time it was Bend Sinister, My
Chemical Romance, Rilo Kiley, The Polyphonic Spree, Immaculate
Machine, . . . And You Will Know Us by the Trail of Dead, The Cribs,
Kaki King, and the CBC Radio 3 stream and podcasts.2
From Bill Dudney
Writing a book is a big task. But of course it’s not just the authors who
work hard to produce the content. The editors (at least the ones who
have corrected my prose) work just as hard if not harder to turn the
technobabble and passive writing into acceptable English, so thanks to
Daniel for helping me over the hump again.
The iPhone engineering team of course deserves a huge thanks for
working nights and weekends to make something that is so much fun
to build for.
The reviewers were also very generous with their time. Many helped,
but a few stick in my mind as being especially helpful, so in no particular
order let me say a hardy thanks to the following people: Tim
Isted, Steven Troughton Smith, Patrick Burleson, Jason Hunter, Andy
Simmons, Marcus Crafter, Tom Hauburger, David Hodge, David Smith,
and Dee Wu. The book is much better for all your hard work!
I’d also like to thank the many folks who have been in the iPhone Studio
for asking just the right question to help me see things from a different
perspective. Those questions and the shift it caused helped to make
this book. Thanks!
My family was also great during the long journey that has been this
book. Thanks to you all for allowing me to stay up late nights and work
2. You can find up-to-date stats at http://www.last.fm/user/invalidname.
ACKNOWLEDGMENTS 21
early mornings (and most of the time in between) to finish this up. I’d
especially like to thank my oldest son, Andrew, who has been a great
help in finding the things that I’m constantly forgetting. And finally, I’d
like to thank the 2,000-year-old Jewish carpenter for making my life
more than I ever thought it would or could be.
We are really excited about this platform and what you are going to
build with your newfound knowledge. It is a great time to be an iPhone
developer, and it’s great to have you as part of the community!
Chapter 2
Hello iPhone
The iPhone is an amazing platform. It’s filled with really cool technology
that makes you want to create. The App Store is filled with applications
that should both inspire and challenge you. The possibilities are practically
endless.
Let’s get started with a simple Hello World application. The rest of the
book will take you through many of the technologies and APIs. You’ll see
everything from location to the accelerometer and from view controllers
to Core Animation. In this chapter, we are going to introduce you to the
tools and the basic development cycle for the iPhone.
Our first application is purposefully simple. We’re going to build an application
that displays the static text “Hello iPhone” on the screen. You’ll
first check that you have all the developer tools you need installed.
You’ll then use two of them to create and run your application in the
iPhone Simulator. Because this is an iPhone app, you’ll rotate the text
when the device is turned sideways. Finally, you’ll download this application
and run it on your iPhone.
2.1 Gearing Up
If you are already developing applications for Mac OS X, then you are
familiar with Xcode, Interface Builder, and the other development tools.
Developing applications for the iPhone will be different because of the
device you are targeting, but many of the tools, APIs, and skills you
will use will be the same. You will be able to breeze through this first
chapter.
GEARING UP 23
Terminology
From here on out when we say iPhone, we mean any iPhone
OS device. So, if you are pushing to an iPod touch, don’t feel
left out, because we mean you too.
If you are coming to the iPhone from another platform—welcome. You
have undoubtedly used an integrated development environment (IDE)
in the past. Xcode fills that role for iPhone developers. Xcode provides
all the features you’d expect such as file management, compilation,
debugging, and error reporting. Once you get to know Xcode, you will
find it as familiar as your existing IDE. If you are completely new to
development, we trust you will find it fun and rewarding.
You will use three main tools all the time in your iPhone development:
Xcode, Interface Builder, and Instruments. You’ll use Xcode to manage
your project and to write, run, and debug your code. You’ll use Interface
Builder to create your interface and to wire it to your code. Instruments
will help you identify areas that are hurting your performance. This
book will not fully plumb the depths of any of these tools. We’ll get
you up and going with each of them and point out features required to
achieve a goal for the app we are building. Any time you would like to
learn more about a particular feature of Xcode, Apple’s documentation
is excellent and is built into Xcode.
Let’s make sure that you have the development tools installed. If you’ve
not already done so, download the iPhone SDK from http://developer.
apple.com/iphone. You need to sign up as an iPhone developer, but
membership is free. Membership and the SDK are free. It’ll cost you
$99 USD to join the iPhone Developer Program, but you’ll need to do
that to get a certificate that allows you to run your applications on the
device.
After you download the package, install it by double-clicking the .dmg
file and then the iPhone SDK package. Follow the on-screen instructions,
and choose the default location to install the developer tools.
When the install is complete, Xcode will be at /Developer/Applications/
Xcode.app. If you choose another root directory to install to, the developer
tools should adjust the path accordingly.
CREATE THE HELLO IPHONE PROJECT 24
Launch Xcode by double-clicking it. You’ll probably want to keep Xcode,
Interface Builder, and Instruments in your Dock for easy access.
When you launch Xcode, you see the friendly welcome screen that is a
great hub of information. Across the top you will notice several sections.
Each one takes you to a different set of kickoff points for documentation
or other helpful information. We use the Xcode News [RSS] section to
keep informed about what new examples and documentation sets Apple
has posted. The iPhone Dev Center is filled with links to the various
sections of the Development Center online. Keep this welcome screen
active at launch for at least a while as you get to know Xcode. Take the
time to poke through each of the sections of the screen and get to know
the content. It’s the best way to learn Xcode.
2.2 Create the Hello iPhone Project
Now that you have Xcode running, create your first project. Select File
> New Project or use D-B- N to launch the New Project Wizard. Select
iPhone OS > Application to see the list of iPhone project templates.
We will explore many of the templates in the examples throughout this
book. For now, choose the View-based Application template, and click
the Choose button.
CREATE THE HELLO IPHONE PROJECT 25
Organizational Groups
Resource List
Editor
Toolbar
Figure 2.1: Hello iPhone project
When the open panel displays, choose a folder, and call the project Hello.
Xcode uses the View-based Application template to make an application
with a single view. Several other files are created for us, but we will look
at many of them later, so don’t worry about them now. You should have
something that looks very similar to Figure 2.1.
On the left side of the window, you see a list of organizational groups.
Each of these containers provides a bucket for you to put stuff into to
help you keep organized. The groups are not implicitly tied to a filesystem
structure, so there is a great deal of flexibility for you to organize
your code and resources in any way you see fit. If you are just getting
started, it is often easier to just learn the initial setup, but if you have
something that works for you, feel free to reorganize to your heart’s
content.
Along the top of the window is the toolbar. This configurable space is
where you can put the commands you most commonly use so that they
are easy to invoke. We have the Overview pull-down menu that allows
us to quickly switch between the iPhone Simulator and the device as
the target to deploy our application on. If you don’t see this Overview
pull-down menu, it’s probably a good idea for you to add it (some develCREATING
A SIMPLE INTERFACE 26
opers are seeing it by default; if it’s already there, you don’t need to do
anything).
To customize your toolbar, select View > Customize Toolbar, or Ctrl+
click in the background of the toolbar and select Customize Toolbar.
Select the Overview item, and drag it to the toolbar. As you drag it up,
the cursor will change to a green circle with the + sign in it. Drop the
Overview item on the left side of the toolbar.
On the right side below the toolbar is the file/resource list. This list
displays files that are part of the group that is selected in the Groups &
Files list on the left. Since the project is currently selected, all the files
in the project are listed. As you click a file in this list, it is displayed
just below in the editor pane. This list tracks the selection in the Groups
& Files list; as you change the selected group, this list will change to
reflect only the files that are part of that group.
The editor pane is where you will be doing most of your editing. It is
where you access most of the code-centric features (completion, refactoring,
and so on).
Now that we have our whirlwind tour of Xcode, let’s run our new application
to see what we get. Click the Build and Go button (or hit DF),
and Xcode will take care of the rest. iPhone applications, like Mac
apps, are special directories called app bundles. During the build process,
Xcode makes an app bundle with your compiled code, and your
resources are copied to the appropriate places in the app bundle.
Now that Xcode has built your app and installed it into the simulator,
the app will launch in the simulator. This first run will be a simple light
gray background (a great flashlight app, if not quite as bright as a white
background). Not much is here yet, which is what we expect given that
we haven’t customized our template yet. Next let’s make some changes
to the interface.
2.3 Creating a Simple Interface
Now it’s time for you to meet Interface Builder. It’s one of the major
tools you will be using to build iPhone apps and the primary tool for
user interface (UI) layout and configuration.
For now, the application isn’t going to do anything, so we don’t need
to write any code. We’ll use visual tools to create the visual interface.
Interface Builder (IB), as the name implies, is responsible for enabling
CREATING A SIMPLE INTERFACE 27
us to build the interfaces that our users interact with. IB understands
the UIKit objects used to make interfaces and the Human Interface
Guidelines (HIG) meant to help us make consistent UIs. It is a very powerful
tool once you get your head wrapped around it. As with Xcode, this
book can’t possibly plumb the depths of IB, but through the experience
you gain building the examples in this book, you will know enough to
dig in and learn it yourself.
Let’s build the interface for your first application. Open HelloViewController.
xib by double-clicking it in Xcode (under the Resources group). We
want to add a label to the interface to contain our “Hello iPhone” text.
So, open the Library with D-B- L (or Tools > Library).
The Library is where you will find all the interface and controller objects
that you can instantiate into your nib file. In this case, we are looking
for a label, so you can type label into the filter field at the bottom of the
window.
CREATING A SIMPLE INTERFACE 28
Drag the label out into the view, and move it until it snaps to the guides
on the left side.
Select the label if it’s not already selected. The little blue circles around
the edge of the label allow you to resize the label. Make it stretch from
the left guide to the right one so it takes the entire width of the view
minus the border recommended by the guides. Also resize the height
to 80 (you can drag with the mouse or just go to the Size inspector
with D- 3 ). Now change the font by pressing D- T and choosing a font
size of 48. Double-click the label to select the text and edit it. Change
it to Hello iPhone. You can also modify the color of the text and add
a shadow and many other attributes in the Attributes inspector (D-
1 ). Also, make sure to specify that you want the text centered in the
Attributes inspector.
Here’s what it looks like with the text centered, turned red, and with a
shadow applied:
Now we are ready to run the application. Save your changes in Interface
Builder. Switch back to Xcode, hit the Build and Go button, and check
out your masterpiece. Once the simulator launches, you should see the
text you set on the label show up in the center of the view on the gray
ROTATING THE TEXT—ADJUSTING THE UI 29
Joe Asks. . .
What Is with XIB and NIB?
Interface Builder understands two file types, .xib and .nib. The
.xib extension is simply the XML version of the .nib file. Since the
.nib file type has been around since Mac OS X 10.0 (and even
before in NeXTStep) and .xib is relatively new, people still refer to
them as nib files. We will do the same throughout the book.
background. In the simulator, choose the menu item Hardware > Rotate
Left or Hardware > Rotate Right. The simulator rotates the device left
or right by 90 degrees, and the text rotates along with it. We’ll make
adjustments so that when the user rotates the device, the text remains
oriented so that we can still easily read it.
2.4 Rotating the Text—Adjusting the UI
You have to perform two basic steps to properly respond when the
device is rotated. You’ll need to set some parameters on the UIView in
Interface Builder, and you’ll have to adjust a single line of code in the
HelloViewController class using Xcode. In this section we’ll make the UI
adjustments, and then in the next section we’ll make the changes to
the code.
Select the label, and use the Size inspector (D-3), under the Autosizing
section, to change the Struts and Springs configuration. Here, we want
to keep the label centered when the device is rotated, so we turn off
Struts for all four edges and turn on Springs for both directions.
The Struts and Springs configuration for views allows us to specify how
the view should act when resized or when the view that contains it is
resized. Struts runs along the outside edges of the view and allows us
to specify that the distance between view and the edges of the view
that contains it (the container view is referred to as the superview)
remains constant. Springs allows us to specify that the view can grow
or shrink in height or width. When the device rotates, the label’s superview
changes size and will therefore update the label according to the
settings we put in place in the Size inspector. You also need to specify
the text alignment on the text field to be centered.
ROTATING THE TEXT—ADJUSTING THE CODE 30
Here are the Struts and Springs configuration with the correct setup:
We are now finished with updating the UI. Let’s go back to Xcode
and make the necessary changes to the code so the app will properly
respond to device rotations.
2.5 Rotating the Text—Adjusting the Code
In Xcode, select the Classes group, and then in the list of files on the
top-right side select the HelloViewController.m file. Xcode will open the file
in the editor pane below the list. Find the shouldAutorotateToInterfaceOrientation:
method (make sure to uncomment it if it’s commented out);
this is where you will change code to make your application understand
that the device has changed orientation.
The iPhone will ask your application whether it wants to rotate by
sending shouldAutorotateToInterfaceOrientation: to it (well, technically this
is not 100 percent accurate, but for now it’s close enough; you will
learn about this in much more detail in Chapter 4, View Controllers, on
page 62). You respond by returning either YES or NO from this method.
If you return YES, the iPhone will rotate your application to the orientation,
and if you return NO, then your app will not rotate.
CODE NAVIGATION 31
Here is the code for this method:
Download HelloiPhone/Hello/Classes/HelloViewController.m
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
Since for this application you want to support all orientations, you just
return YES. We have updated the UI and the code, so now it’s time to
run; click the Build and Go button in Xcode to launch the application.
Once it’s launched, use D-! and D- to get the simulator to rotate.
The label stays centered in the view and changes its orientation along
with the device.
2.6 Code Navigation
We didn’t have much code in this example. As your projects become
larger and your classes grow, you will want better ways to quickly navigate
your source code with Xcode. Once you have selected a file in the
list, it is opened for you in the editor pane. The pane has several buttons
along the top that give us a bunch of tools to navigate around in
the code. Click the symbols pull-down menu to navigate immediately to
any symbol.
RUNNING YOUR APP ON YOUR IPHONE 32
A simple click of the symbols list will display the symbols in the order
they are found in the file. If it’s easier to find what you are looking
for from an alphabetically ordered list, you can hold down the option
key and click the symbol list; then Xcode will display the symbols in
alphabetical order.
2.7 Running Your App on Your iPhone
The simulator is a fine place to experiment, but there is no substitute
for pushing the code to your device and watching it react in your hands.
Unfortunately, you won’t be able to push to your phone until you have
received your developer certificates from Apple. If you already have your
certs installed, then the rest of this chapter takes you through the steps
to get your app pushed onto your device.
If you don’t have them installed and you are ready to get started, start
with iPhone Developer Program [App08c] where you can apply for the
program. Once accepted, you can go to Obtaining Your iPhone Development
Certificate [App08f] to get more information about putting your
certificates onto your devices and using them to sign your code from
Xcode. If you don’t have your certs, then please skip to the next chapter
because the remainder of this chapter won’t make much sense.
The change required to your project in Xcode is minimal to deploy an
app to your phone. First you have to specify the proper application
identifier in your project properties. Select the Hello target, hit D- i (or
right-click and choose Get Info), and then choose the Properties tab.
The identifier you use has to match one of the provisioning profiles you
set up with your iPhone developer certificates. We created a specific
provisioning profile for use with the examples in this book and suggest
you do the same. If you don’t want to make a specific profile, then feel
free to change the identifier to one that matches an existing profile.
On the next page, we show the setup we used for this example.
RUNNING YOUR APP ON YOUR IPHONE 33
Now you need to change from running in the simulator to running on
the device. Select the Overview pull-down menu. Under the Active SDK
list, choose Device – iPhone OS X (where X is the version installed on
the device).
RUNNING YOUR APP ON YOUR IPHONE 34
If you don’t see this item, you probably have a problem in your developer
certificates. Log onto the iPhone developer portal site, and review
the direction in Obtaining Your iPhone Development Certificate [App08f]
to make sure you have followed all the appropriate directions to get the
certificates installed and working.
Once you have selected the device, click the Build and Go button again.
This will take a few seconds to complete because Xcode has to rebuild
all your code for running on the iPhone processor instead of for the processor
on your Mac. Once it’s done compiling, packaging, and signing
your application, Xcode installs the application onto your device and
starts it. Once it’s started, try rotating the device to see how the “Hello
iPhone” text follows when the device is rotated.
Congratulations! You have completed building and running your very
own iPhone application. You have seen a bit of Xcode and IB and how
the two tools are used to build the code and the interface for your
applications.
Chapter 3
iPhone Development
Fundamentals
Now that you’ve had a chance to get a simple application up and running
with the iPhone SDK tools, let’s take a step back and understand
how we got here. In this chapter, we’ll take a look at the organization
of the iPhone’s application stack, how the tools work in relationship
to this architecture, and some of the concepts you’ll need to master in
pretty much any nontrivial iPhone application.
We barely touched the code in the previous chapter—we’re going to
dive more deeply into it now. iPhone applications are primarily written
in Objective-C, a set of object-oriented extensions to the classic C
language.
Our goal in this book is to make Objective-C programming for the
iPhone understandable to developers with experience in any of the various
C-based, curly-brace languages. If you’ve worked with C++, C#,
or Java, many of Objective-C’s concepts will be familiar to you, even if
the syntax isn’t. If your primary background is in scripting languages
like Ruby, Python, or JavaScript, we expect that you’ll be familiar with
the concepts of object orientation, but some of the latent subtle Cisms,
particularly involving pointers and memory management, may
take some getting used to.
We will cover Objective-C’s everyday essentials in this chapter, and if
you want to dig deeper, you might want to look at Apple’s The Objective-
C 2.0 Programming Language [App09e], Bill’s “Coding in Objective-C
2.0” screencasts at http://www.pragprog.com/screencasts, or a book on
THE IPHONE SOFTWARE ARCHITECTURE 36
Cocoa for the Mac, such as Daniel Steinberg’s Cocoa Programming:
A Quick-Start Guide for Developers [Ste09], also from the Pragmatic
Programmers.
3.1 The iPhone Software Architecture
The iPhone’s software stack is divided into a number of layers, with
your application at the highest level of abstraction and core system
services at the lowest level. From highest to lowest level, the stack can
be summarized as follows:
• Your application.
• Cocoa Touch—A framework for developing touchscreen applications:
UI elements, event dispatching, application life cycle, and
so on. This also includes object wrappers around essential data
types (strings, collections).
• Media—Graphics, animation, sound, video.
• Core services—Collections, strings, location awareness, SQLite
database, Address Book, networking, and so on.
• Core OS layer—Unix services, standard I/O, threads, BSD sockets,
power management, and so on.
You’ll mostly want to work primarily with the GUI frameworks and the
OO abstractions offered by the Cocoa Touch layer, and it’s this layer
that we primarily discuss in this book (with diversions deeper into the
stack as necessary for specific topics). Most of the Cocoa Touch classes
are designed to be called directly from your code; you can subclass
these classes to add functionality, but you’ll find that you need to do
this far less frequently than in other languages.
3.2 Coding in Objective-C
The Cocoa Touch frameworks you’ll be using are written in and called
with Objective-C, which is a superset of the original C. Because of this,
you can and will freely mix C and Objective-C syntax in your application
code.
Classes in Objective-C are developed by creating a header file and an
implementation file. These two files share the same name but different
CODING IN OBJECTIVE-C 37
Joe Asks. . .
Do I Have to Learn C to Write iPhone Applications?
Well, we’re not going to advise you to drop this book and read
“K&R” first, but if you’re not already familiar with C, you will
surely be picking up some of it along the way.
Some iPhone APIs developed outside of Apple are used with
what we’d describe as typical C coding practices. These
include OpenGL, OpenAL, and SQLite. There are also Apple
APIs called with plain C (Apple often uses the term procedural
C to distinguish it from Objective-C) that use Apple-specific
design patterns to craft an OO-like experience. These include
Core Foundation, Core Audio, and Quartz/Core Graphics,
which will be introduced in Section 17.1, Using the Procedural-C
APIs, on page 364.
Even within purely Objective-C Cocoa APIs, you’ll use C syntax
for things such as control flow, and you’ll encounter C idioms,
such as using pointers for all your Objective-C variables, providing
their addresses (with the & operator) as a parameter to get
return values from method parameters, variable-length argument
lists, and so on.
We learned C a long time ago, but we’re sympathetic to how
hard it is to go from modern languages back to C’s functional
style and memory management. We’ll try to make sure to warn
you of C’s idiosyncracies as we proceed.
. This is the short name for Brian Kernighan and Dennis Ritchie’s much-cited
The C Programming Language [KR98].
extensions; to create a class called Person, you would create both a Person.
h file and a Person.m file. In the header file, you include the public
parts of your class: the names and types of your instance variables and
your method signatures, which describe the return type and parameters
of a method. In the implementation file, you then implement these
methods with code, declaring and using any needed local variables that
are relevant only to the implementation and are not meant to be seen
by other classes. Like C, you also need to indicate where the compiler
can find other code you’re using, by importing the header file of classes
you refer to in your headers or implementation.
ESSENTIAL COCOA TOUCH CLASSES 38
In Objective-C, method calls actually represent messages dispatched
by a small, lightweight runtime to the objects in memory. This is a
subtle but important distinction, which allows for surprisingly dynamic
behavior in what might initially seem like a fairly formal language. For
example, if you call a method on an object reference that turns out to be
nil, you don’t crash or get an error (like Java’s NullPointerException); the
runtime realizes that sending a message to a nonexistent object would
be meaningless and simply does nothing.
Typical Objective-C method calls are enclosed in square braces, beginning
with the object and followed by parameter names and the values
you’re providing for those parameters. For example, if you had an
NSString instance called myString, you would get its third character with
a method invocation like this:
myChar = [myString characterAtIndex: 3];
The most significant difference from other languages, other than the
square braces, is that the parameters are always named with the
parameter-and-colon construct called a keyword. It does mean more
typing, but it makes code a lot easier to read, compared to other C-like
languages where you could have a half dozen parameters within a set
of parentheses and no readily apparent idea what each one represents.
3.3 Essential Cocoa Touch Classes
Now that you know you’ll be doing most of your coding in Objective-
C, let’s take a quick look at the classes provided in the iPhone SDK
frameworks.
The Cocoa Touch application frameworks, first mentioned above in Section
3.1, The iPhone Software Architecture, on page 36, contain most of
the classes you will use to develop your first applications. The term
comes from Cocoa, the object-oriented frameworks developed for Mac
OS X programming (and NextStep before that), along with GUI classes
uniquely designed for use on a mobile, touchscreen device (hence the
“Touch”).
Cocoa’s Foundation framework includes essential data classes, includes
basic utilities, and establishes some core programming conventions
that cannot be expressed by the Objective-C language alone, such as
techniques for managing memory (which we’ll visit in Section 3.7, ManESSENTIAL
COCOA TOUCH CLASSES 39
aging Application Memory, on page 56). Nearly all Cocoa classes inherit
from a root class, NSObject, defined in Foundation.
Perhaps the first and most important thing to discover in Foundation is
its data management classes, which are used throughout Cocoa instead
of the procedural C equivalents. For example, the traditional C string,
the null-terminated char array, is almost never used in Cocoa. Instead,
you use NSString, which represents not only the character data but also
its encoding; with rich support for Unicode (and the UTF-8 and UTF-
16 encodings), the NSString makes it easy to handle text in any of the
dozens of character sets on the iPhone.
Cocoa also provides a deep set of collection classes, obviating the need
for most uses of C arrays (or hand-rolled collections, such as linked lists
and hashtables). Three classes are used for collecting Cocoa objects:
NSArray for ordered collections of objects, NSSet for unordered collections,
and NSDictionary for mapping key objects to value objects. These
three collections are immutable—once initialized, they can’t be changed.
If you want to add, delete, or otherwise change their contents, use
the mutable subclasses NSMutableArray, NSMutableSet, and NSMutable-
Dictionary.
The collections can store only NSObjects. If you have C primitives, you
can pass them around Cocoa with the wrapper classes NSData and
NSMutableData, which wrap a byte buffer, and NSNumber, an object container
for any of C’s scalar (numeric) types, such as int, float, or bool.
Cocoa has a few more specific data classes, including NSURL for URLs
(including file://-style URLs representing items on the local filesystem,
though you often use NSString paths too), and timekeeping classes such
as NSDate and NSTimeZone.
The “Touch” part of Cocoa Touch is largely represented by the UIKit
framework, also imported by default in every iPhone application. This
framework offers the drawing model, event handling, application life
cycle, and other essentials for a touch-based application. You’ll largely
interact with it through the various user interface component classes it
provides: UIButton, UITextView, UITableView, and so on.
WORKING WITH XCODE AND INTERFACE BUILDER 40
Between the data types in Foundation and the UI components in UIKit,
Cocoa Touch gives you a great foundation on which to start coding your
application.1
3.4 Working with Xcode and Interface Builder
Now you might be thinking, “Hey, I barely wrote any code to create the
application in the previous chapter, so why are we talking about code
all of a sudden?” Fair enough. We’ve already introduced you to Xcode
and Interface Builder as your primary tools, so let’s take a look at the
roles they play by looking at the contents of the Hello.xcodeproj project
you created in Chapter 2, Hello iPhone, on page 22. With the project
open in Xcode, you should have a window whose left side shows the
Groups & Files list, which presents the contents of Hello as a set of
folders. With Hello clicked, you’ll see all the files listed in the right pane,
but by clicking each folder individually, you can examine the parts of
the project by type:
• Classes—Class files are the C and Objective-C source that you
create to provide the functionality of your application. The template
you used to create Hello set up two classes for you: HelloAppDelegate
is responsible for handling life-cycle events (such as the
application starting up or shutting down), and the HelloViewController
manages what you see on-screen.
• Other sources—These are source files that are generated automatically
and that you are largely not responsible for or interested
in. HelloPrefix.pch is the precompiled headers file, created by Xcode
to speed up processing of header files in your build. main.m is
the implementation of the main( ) function that the system calls
to launch your application. You could also put third-party library
source here or procedural-C sources (.c files) that aren’t “classes”
per se.
• Resources—Resources are noncode files that are nevertheless
needed by your application at runtime. Such files might include
graphics or sound files, localization dictionaries, and the like. In
1. Keep in mind that you can learn more about these classes at any time from Xcode’s
Help menu. See Section 27.3, Using iPhone SDK Documentation, on page 493 for an
overview of Xcode’s documentation viewers.
WORKING WITH XCODE AND INTERFACE BUILDER 41
this project, the Info.plist2 file includes basic settings for the application
such as its icon and name. The resources also contain the
nib files that contain the “freeze-dried” GUI components used to
present the user interface. You edited the HelloViewController.xib file
with Interface Builder in the previous chapter.
• Frameworks—These represent the frameworks that your application
uses. By default, the Xcode template links in the frameworks
Core Graphics and UIKit so you’ll be able to call the various
GUI classes, and Foundation for commonly used classes such as
strings, collections, URLs, and the like. In later chapters, when we
go beyond basic functionality, we’ll add more frameworks to this
folder.
• Products—This folder represents the files that will be created by
the build process, in this case the Hello.app iPhone application.
Xcode is really the base for your application project. Although you’ll
use other applications to set up the GUI elements in the nib (Interface
Builder), create images (any graphics application such as Photoshop or
Pixelmator), and measure performance (Instruments), the job of managing
all the pieces of the application and building it falls to Xcode.
Typically, Xcode also provides your source editing, though you can configure
external applications (perhaps BBEdit, TextMate, or even emacs)
to do your source editing if you so desire.
Designing an Interactive Application
Our first application said “Hello iPhone,” so let’s return the favor by
saying hi to the user. This will require prompting the user for their
name.
Close out the Hello project by closing the project window if it’s still open,
and use DBN to create a new project. In the New Project window, you’ll
again choose a View-based Application, and when you’re asked to name
the project, choose a new name like HelloUser.
Just like in the previous chapter’s example, the template project provides
us with two classes (HelloUserAppDelegate and HelloUserViewCon-
2. Starting in iPhone SDK 3.0, Xcode prepends the project name to the filename, like
Hello-Info.plist. We’ll continue to use the term Info.plist as a generic reference to whatever file
was created for your application’s settings.
WORKING WITH XCODE AND INTERFACE BUILDER 42
troller), along with a few other classes that we’ll explain in the next section.
For now, it’s enough to know that in a single-view application, we
put stuff on-screen by working with the HelloUserViewController class and
its associated HelloUserViewController.xib, which contains the freeze-dried
GUI for this class. In the previous chapter, we edited only the .nib file,
but this time, we’re going to want to customize the class to provide
some interactivity.
Declaring IBOutlets and IBActions
Our new application lets the user type his or her name into a text field.
When they’re done, we’ll customize the message with the name. So, if
you type Quinn, the label will change to “Hello Quinn.” To do this, we will
use a label for the message, a text field for the user’s name, a button to
accept the input, and a method that updates the label when the button
is tapped.
To make this work, we need to create relationships between the logic
of the application and the GUI objects in the nib. We’ll use special keywords
when we declare variables that refer to objects in the nib and
when we declare methods to be called from events in the user interface,
such as button taps. A reference from code to an object in the nib is
called an outlet and is designated with the keyword IBOutlet. Similarly,
a method that you want a nib’s objects to be able to call is an action
and is designated with the keyword IBAction.
Typically, you declare outlets and actions in code so that IB will be able
to use them. Edit your HelloUserViewController.h header file so it looks like
this:
Download HelloiPhone/HelloUser/Classes/HelloUserViewController.h
Line 1 #import
-
- @interface HelloUserViewController : UIViewController {
-
5 IBOutlet UILabel *helloLabel;
- IBOutlet UITextField *nameField;
-
- }
-
10 - (IBAction) sayHello: (id) sender;
-
- @end
WORKING WITH XCODE AND INTERFACE BUILDER 43
This code declares two outlets and one action. Since the outlets are
variables and therefore part of the class structure, they go in the curlybrace
block of the @interface declaration. The first outlet, on line 5,
declares a pointer to a UILabel called helloLabel, with the additional IBOutlet
declaration signaling our desire to connect this reference to an object
created in Interface Builder. With this connection, we’ll be able to style
the label in Interface Builder, and also alter it from code at runtime,
in order to display the customized hello message. Similarly, on line 6,
we declare a UITextField as an IBOutlet, so we’ll be able to read its value
from code. Finally, on line 10, we declare a method that will handle the
button tap, and we declare it to be an action (note that we don’t need
an outlet to the button if we’re not going to be manipulating it, such as
changing its size or text, from code).
As you can see, method declarations in Objective-C have a unique syntax.
They start with a single character (-) to declare an instance method,
meaning that it is called on and applies to a single instance of the class,
or + for a class method, which is independent of an instance. Following
this is the return type in parentheses. (IBAction) is equivalent to (void)
in that it returns no value, but using the IBAction keyword indicates
our intent to connect the method to GUI events via Interface Builder.
Finally, the arguments are provided as pairs of types and parameter
names. In this case, the (id) type is a pointer to any object; the pattern
(id) sender is used for all IBAction declarations so the called method can
know what object (the sender) has called it.
Laying Out Your Interface in IB
Now you’re ready to create the GUI in Interface Builder and connect
its components to your code. First save the header file, if you haven’t
already.
Next, in Xcode’s project window, double-click HelloUserViewController.xib
to open it with IB. As in the previous chapter, IB will show a document
window with three objects: two proxy objects (File’s Owner and First
Responder, which we’ll explain later) and View. The view’s preview window
may already be open; if not, double-click View to open it. Your view
starts as a blank area precisely the size of the iPhone screen. From the
library, drag over three objects: a label, a text field, and a button.
WORKING WITH XCODE AND INTERFACE BUILDER 44
Your preview should look something like this:
Obviously, this GUI could use a little bit of layout and polish. Let’s
customize the three components as follows:
• Select the label to show its handles, and drag the right and left
edges until the dashed blue margin lines appear. This will let the
label span all the way across the screen in case the user has
a really long name. To center the text, bring up the Attributes
inspector (D1), and where it says Alignment, click the “center text”
icon (the middle one).
• Select the text field, and drag its edges to the margins too. In
its Attributes inspector, you can use the placeholder to provide
WORKING WITH XCODE AND INTERFACE BUILDER 45
a grayed-out visual cue to tell the user what they should do with
the text field, for example, Name.
• Finally, double-click the button, or edit its Title attribute, to set
the button’s text to Say Hello.
Here’s the completed GUI. For simplicity, we won’t worry about supporting
rotation or resizing the components in this sample.
Now that we’ve set up our user interface, we’re ready to connect it to
our code. To do this, go back to the HelloUserViewController.xib document
window and its three icons. We’re going to be working with the File’s
Owner icon. This isn’t a real object but, instead, a proxy object that
represents an object assigned to be the “owner” of the nib when the nib
is loaded.
0 comments:
Post a Comment