In this chapter, we're going use Xcode and Interface Builder to create a small iPhone application to display the text “Hello, World!” on its screen.. We'll look at what's involved in cre
Trang 1Appeasing
the Tiki Gods
s you're probably well aware, it has become something of a tradition to call
the first project in any book on programming “Hello, World!”We considered
breaking this tradition but were scared that the Tiki gods would inflict some
painful retribution on us for such a gross breach of etiquette So let’s do it by
the book, shall we?
In this chapter, we're going use Xcode and Interface Builder to create a small
iPhone application to display the text “Hello, World!” on its screen We'll look
at what's involved in creating an iPhone application project in Xcode, work
through the specifics of using Interface Builder to design our application's user
interface, and then run our application on the iPhone simulator After that,
we'll give our application an icon and a unique identifier to make it feel more
like a real iPhone application
We've got a lot to do here, so let’s get going
Setting Up Your Project in Xcode
By now, you should have Xcode and the iPhone SDK installed on your machine
You should also download the book projects archive from the Apress web site
Here’s a link to the book page:
http://www apress.com/book/view/9781430216261
Look for the Source Code link in the Book Extras section on the left side of the
page Expand the archive, and place the project folder in a convenient location
Trang 2Even though you have the complete set of project files at your disposal, we think you'll get more out of the book if you create each project by hand instead of simply running the ver- sion you downloaded The biggest reason for this is the familiarity and expertise you'll gain
in working with the various tools we use throughout the book if you roll your own projects There's just no substitute for actually clicking and dragging out buttons and sliders and
scrolling through source code to make changes as we move from one version of a program
to another
That said, our first project is in the 02 Hello World folder If you'll be creating your own proj- ects, create a new 02 Hello World folder and follow along
Launch Xcode, which is located in /Developer/Applications |f this is your first time using Xcode, don’t worry; we'll walk you through the process of creating a new project If you're
already an old hand, just skim ahead
When you first launch Xcode, you'll be presented with a welcome screen like the one shown
in Figure 2-1 The welcome screen contains useful links to iPhone and Mac OS X technical
documentation, tutorial videos, news, sample code, and lots more All of this information
is available on Apple’s developer web site and within Xcode’s documentation browser, so
if you'd rather not see this screen in the future, just uncheck the Show at Launch checkbox
before closing it If you feel like poking through the information here for a few minutes, by
all means, go right ahead When you're done, close the window, and we'll proceed
Getting Started iPhone Dev Center Mac Dev Center Xcode News [RSS] Mailing Lists Tips
Welcome to Xcode 3.1
Create your first Cocoa application
To get started with Xcode, run the New Project assistant and create a new Cocoa project Learn how easy it is to quickly create, build, and run your first
Mac application
Build your user interface Xcode projects store the interface in a graphically-designed NIB file, separate
from your implementation code Learn how Interface Builder works with Xcode
to design your UI and wire your code to the visual controls
Store your application data Xcode works with Cocoa to elegantly wire together separate user interface,
implementation code, and persistent data using Core Data Learn how Core Data
makes storing Cocoa application data simple, yet incredibly powerful
a x Optimize your application
( lự 7 steht ) Xcode tightly integrates with performance analysis tools, making it easy to
W gather performance data and tune your application Learn how the Instruments
{ } analysis tool can help you get the most of your application
Figure 2-1 The Xcode welcome screen
Trang 3OTE
If you have an iPhone or iPod Touch connected to your machine when you first launch Xcode, you might see a message asking if you want to use that device for development For now, click the /gnore button If you choose to join the paid iPhone Developer Program, you will gain access to a program portal that will tell you how to use your iPhone or iPod Touch for development and testing
Create a new project by selecting New Project from the File menu, or by pressing 1*88N, which will bring up the New Project Assistant (see Figure 2-2)
Choose a template for your new project:
pplication
& Mac OS X Navigation-Based OpenGL ES Tab Bar
Application Application Application Application
Audio Units
Automator Action s; m về
Command Line Utility Utility Application Window-Based
Dynamic Library Application Application
Framework
java
Kernel Extension Description This template provides a starting point for an application
Standard Apple Plug-ins that uses a single view It provides a view controller to
Static Library manage the view, and a nib file that contains the view
Other
( Cancel 3 ( Choose )
Figure 2-2 The New Project assistant, which lets you select from various file
templates when creating a new file
As you'll see in Figure 2-2, the pane on the left side of the window is divided into two main sections: iPhone and Mac OS x You'll notice that there are a number of project template cat- egories available for Mac OS X, but only one category (at least at the time of this writing) for the iPhone: Application
As we did in Figure 2-2, select Application from under the iPhone heading, and you'll be shown a number of icons in the upper right pane, each of which represents a separate project template that can be used as a starting point for your iPhone applications The icon labeled View-Based Application is the simplest template and the one we'll be using for the first several chapters The others provide you with additional code and/or resources needed to create
Trang 4common iPhone application interfaces and contain stuff we're not ready to look at yet, but don’t worry, we'll get to them later
For this first project, click the View-Based Application icon (that icon is selected in Figure 2-2) and then click the button labeled Choose
Once you've selected your project template, you'll be asked to save your new project using the standard save sheet (see Figure 2-3) Type Hello World for the project name, and save it wherever you want it stored The Document folder is not a bad place, but you might want to create a dedicated folder for your Xcode projects
Choose ae Save As: | Hello World| JS
mm
mm
iPhone ¢ Where: í A Documents
Application
lon
=
Application
Audio Units
Command Line Utility Utility Application View-Based Window-Based
Dynamic Library Application Application
Framework
Java
Kernel Extension ; Description This template provides a starting point for an application
Standard Apple Plug-ins that uses a single view It provides a view controller to
Static Library manage the view, and a nib file that contains the view
Other
Figure 2-3 Selecting the name and location for your project
The Xcode Project Window
After you dismiss the save panel, Xcode will create and then open your project and a new project window will appear that looks like Figure 2-4 We find that the project window, when first created, is a little small for our tastes, and we usually expand the window to take up more of the screen There's a lot of information crammed into this window, and it’s where you will be spending a lot of your iPhone development time
Your project window features a toolbar across the top, which gives you ready access to a lot
of commonly used commands Below the toolbar, the window is divided into three main
sections, or panes.
Trang 5
Z“== :‹
ILO: serins wars
|e | PAR LL B §@ Foundation.framework Mã
> (Classes {A Hello World.app Bly
> (| Other Sources [al Hello_World_Prefix.pch
> {_) Resources A Hello_WorldAppDelegate.h
> (_)] Frameworks [m| Hello_WorldAppDelegate.m v w
> (J) Products [s] Hello_WorldViewController.h
> 4 Executables [al Hello_WorldViewController.xib 8w
vQ Find Results = —" — ” — TC Ta
> LJ] Bookmarks :
@® Project Symbols H
> (gj Implementation Files
` li NIB Files
Figure 2-4 The Hello World project in Xcode
The pane that runs down the left side of the window is called the Groups & Files pane All of the resources that make up your project are grouped here, as are a number of relevant proj- ect settings Just as in the Finder, clicking the little triangle to the left of an item expands that item to show available subitems Click the triangle again to hide the subitems
The top right pane is called the Detail View and shows you detailed information about items selected in the Groups & Files pane The lower right pane is called the Editor pane If you select a single file in either the Groups & Files or Detail pane, and Xcode knows how to display that kind of file, the contents of the file will be displayed here Editable files, such as source
code, can also be edited here In fact, this is where you will be writing and editing your appli- cation’s source code
Now that we have the terminology out of the way, take a look at the Groups & Files pane The first item in the list should bear the same name as your project, in this case, Hello World This item is the gathering point for the source code and the other resources specific to your proj- ect For the time being, don’t worry about the items in the Groups & Files pane except those under Hello World
Trang 6Take a look at Figure 2-4 Note that the disclosure triangle to the left of Hello World is open, and there are five subfolders: Classes, Other Sources, Resources, Frameworks, and Products Let's briefly talk about what each subfolder is used for
m@ Classes is where you will soend much of your time This is where most of the code that you write will go, since this is where all Objective-C classes rightfully belong You are free to create subfolders under the Classes folder to help organize your code We'll be using this folder starting in the next chapter
@ Other Sources contains source code files that aren't Objective-C classes Typically, you won't spend a lot of time in the Other Sources folder When you create a new iPhone application project, there are two files in this folder:
O Hello World_Prefix.pch: The extension pch stands for “precompiled header.” This is
a list of header files from external frameworks that are used by our project Xcode will precompile the headers contained in this file, which will reduce the amount of time it takes to compile your project whenever you select Build or Build and Go
It will be a while before you have to worry about this, as the most commonly used header files are already included for you
O main.m: This is where your application’s main() method is You normally won't need to edit or change this file
m Resources contains noncode files that will be included as part of your application This
is where you will include things like your application’s icon image and other images, sound files, movie files, text files, or property lists that your program may need while it’s running Remember, since your application runs in its own sandbox, you will have
to include any files you need here, because you won't be able to access files located elsewhere on the iPhone except through sanctioned APIs, such as the ones that pro- vide access to the iPhone’s photo library and address book There should be three items in this folder:
O Hello_WorldViewController.xib: This file contains information used by the program Interface Builder, which we'll take for a spin a bit later in this chapter
0 Info.plist: This is a property list that contains information about our application We'll look at this file a little bit later in the chapter too
O MainWindow.xib: This is your application’s main Interface Builder (or “nib”) file In
a simple application like the one we're building in this chapter, there’s often no need to touch this file In later chapters, when we design more complex interfaces,
we will work with this file and look at it in more depth
Trang 7m Frameworks are a special kind of library that can contain code as well as resources
such as image and sound files Any framework or library that you add to this folder
will be linked in to your application, and your code will be able to use objects, func- tions, and resources contained in that framework or library The most commonly needed frameworks and libraries are linked in to our project by default, so most of the time, we will not need to do anything with this folder Less commonly used libraries and frameworks, however, are not included by default, and you will see how to link to them into an application later in this book
m@ Products contains the application that this project produces when it is compiled If you expand Products, you'll see an item called Hello World.app This is the application that this particular project creates Hello World.app is this project’s only product Right now, Hello World.app is listed in red, which means that the file cannot be found, which makes sense, since we haven't compiled our project yet! Highlighting a file’s name in red is Xcode’s way of telling us that it can’t find the underlying physical file
OTE
These “folders” under your project in the Groups & Files pane do not necessarily correspond to folders on your Mac’s file system These are logical groupings within Xcode to help you keep everything organized and to make it faster and easier to find what you're looking for while working on your application If you
look into your project's folder, you'll notice that while there is a Classes folder, there is no folder called Other Sources or Resources Often, the items contained in those two project folders are stored right in the project's root directory, but you can store them anywhere, even outside of your project folder if you wish The hierarchy inside Xcode is completely independent of the file system hierarchy Moving a file out of the Classes folder in Xcode, for example, will not change the file’s location on your hard drive
Introducing Interface Builder
Now that you're familiar with the basics of Xcode, let’s take a look at the other half of the dynamic duo used in iPhone software development: Interface Builder, commonly referred
to as IB
In your project window's Groups & Files list, expand the Resources group, and then
double-click the file Hello_WorldViewController.xib This will open that file in Interface Builder
If this is your first time using Interface Builder, a window grouping similar to that shown in Figure 2-5 should appear If you've used Interface Builder before, the windows will be where you left them the last time you used it
Trang 8
@ = Interface Builder File Edit Font Layout Tools Window
0Ø Hello_WorldViewControlle i © = Lib ibrary
View Mode Info Search Field > | Library
g TOTEM Ie
v Navigation Controller - A controller
hierarchy of views
Á — Tab Bar Controller - A controller that
iN ca ) manages a set of view controllers that represent tab bar items
O Hello World.xcodeproj
+ ®-
á ) Table View Controller - A controller
(=) Image Picker Controller - A controller
Ê 23577 that manages views for choosing and
‘staking pictures
ae
objects and controllers not directly
è Object - Provides a template for available in Interface Builder
for an object that exists outside of the +
J rỉ at
“he ( View Controller { 7 UlViewController Provides view-management functionality for
toolbars, navigation bars, and application views
The UIViewController class also supports modal
views and rotating views when device orientation changes
Figure 2-5 Hello_ WorldViewController.xib in Interface Builder
OTE
Interface Builder has a long history; it has been around since 1988 and has been used to develop applica- tions for NextSTEP, OpenSTEP, Mac 0S X, and now iPhone Interface Builder supports two file types: an older format that uses the extension nib and a newer format that utilizes the extension xib The iPhone project templates all use xib files by default, but until very recently, all Interface Builder files had the
extension nib, and as a result, most developers took to calling Interface Builder files “nib files.” Interface
Builder files are commonly called nib files regardless of whether the extension actually used for the file is .xib or nib In fact, Apple actually uses the terms “nib” and “nib file’ throughout its documentation
The window labeled Hello_WorldViewController.xib (the upper left window in Figure 2-5) is the nib’s main window It is your home base and starting point in this particular nib file With
the exception of the first two icons (Files Owner and First Responder), every icon in this win-
dow represents a single instance of an Objective-C class that will be created automatically
for you when this nib file is loaded
Trang 9Want to create an instance of a button? You could, of course, create the button by writing
code But more commonly, you will use Interface Builder to create the button and specify its attributes (shape, size, label, etc.)
The Hello_WorldViewController.xib file we are looking at right now gets loaded automatically when your application launches—for the moment, don’t worry about how—so it is an excel- lent place to create the objects that make up your user interface
For example, to add a button to your application, you'll need to instantiate an object of type UIButton You can do this in code by typing a line like this:
UTButton *myButton = [[UIButton alloc] initWithFrame:aRect];
In Interface Builder, you can accomplish the same exact thing by dragging a button from
a palette of interface objects onto your application’s main window Interface Builder makes
it easy to set the button’s attributes, and since the button will be saved in the nib file, the button will be automatically instantiated when your application starts up You'll see how this works ina minute
What’s in the Nib File?
Take a look at Figure 2-5 As we mentioned earlier, the window labeled Hello_
WorldViewController.xib (the upper left window) is the nib file’s main window Every nib file starts off with the same two icons, File’s Owner and First Responder They are created auto- matically and cannot be deleted From that, you can probably guess that they are important, and they are
Files Owner will always be the first icon in any nib file and represents the object that loaded the nib file from disk In other words, File’ Owner is the object that “owns” this copy of the
nib file If this is a bit confusing, don’t worry; it’s not important at the moment When it does become important later on, we'll go over it again
The second icon in this and any other nib file is called First Responder We'll talk more about
responders later in the book, but in very basic terms, the first responder is the object with
which the user is currently interacting If, for example, the user is currently entering data
into a text field, that field is the current first resoonder The first responder changes as the user interacts with the interface, and the First Responder icon gives you a convenient way to
communicate with whatever control or view is the current first responder without having
to write code to determine which control or view that might be Again, we'll talk about this much more later on, so don't worry if this concept is a bit fuzzy right now
Trang 10Every other icon in this window, other than these first two special cases, represents an object instance that will be created when the nib file loads In our case, as you can see in Figure 2-5,
there is a third icon called View
The View icon represents an instance of the UIVi ew class A UIVi ew object is an area that
a user can see and interact with In this application, we will only have one view, so this icon represents everything that the user can see in our application Later on, we'll build more complex applications that have more than one view, but for now, just think of this as what the users can see when they’re using your application
OTE
UIVi ew, and this application has only one of those
Technically speaking, our application will actually have more than one view All user interface elements that can
be displayed on the screen, including buttons, text fields, and labels, are all subclasses of UIVi ew When you see the term “view” used in this book, however, we will generally be referring only to actual instances of
If you go back to Figure 2-5, you'll notice two other windows
open besides the main window Look at the window that has
the word View in the title bar That window is the graphical
representation of that third icon in the nib’s main window If
you close this window and then double-click the View icon in
the nib file’s main window, this window will open up again
This is where you can design your user interface graphically
Let’s do that now
Adding a Label to the View
The rightmost window shown in Figure 2-5 is the library,
which you can see in more detail in Figure 2-6 This is where
you will find all the stock Cocoa Touch objects that Inter-
face Builder supports Dragging an item from the library to
a nib file window will add an instance of that class to your
application If you close the library window, you can get it
to reappear by selecting Library from the Tools menu The
items on this palette are primarily from the iPhone UIKit,
which is a framework of objects used to create an applica-
tion’s user interface
( Objects | Media
> | jjj Library
TOTTI TOT OTe
=>
Navigation Controller - A controller that manages navigation through a hierarchy of views
Tab Bar Controller - A controller that manages a set of view controllers that represent tab bar items
J Table View Controller - A controller that manages a table view
JS
<> Image Picker Controller - A controller E8 that manages views for choosing and taking pictures
+ Object - Provides a template for
- objects and controllers not directly
“” available in Interface Builder
| Proxy Object - Provides a placeholder A Aciumant
View Controller UIViewController
—
Provides view-management functionality for toolbars, navigation bars, and application views The UlViewController class also supports modal views and rotating views when device orientation changes
Figure 2-6 The Library palette,
where you'll find stock objects
from the UIKit that are available for use in Interface Builder