Professional Documents
Culture Documents
Xcode Quick Tour Iphone OS
Xcode Quick Tour Iphone OS
2008-10-15
ASSUMING THE ENTIRE RISK AS TO ITS QUALITY
AND ACCURACY.
Apple Inc.
IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT,
© 2008 Apple Inc. INDIRECT, SPECIAL, INCIDENTAL, OR
All rights reserved. CONSEQUENTIAL DAMAGES RESULTING FROM ANY
DEFECT OR INACCURACY IN THIS DOCUMENT, even
if advised of the possibility of such damages.
No part of this publication may be reproduced, THE WARRANTY AND REMEDIES SET FORTH ABOVE
stored in a retrieval system, or transmitted, in ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL
any form or by any means, mechanical, OR WRITTEN, EXPRESS OR IMPLIED. No Apple
dealer, agent, or employee is authorized to make
electronic, photocopying, recording, or any modification, extension, or addition to this
otherwise, without prior written permission of warranty.
Apple Inc., with the following exceptions: Any Some states do not allow the exclusion or limitation
person is hereby authorized to store of implied warranties or liability for incidental or
consequential damages, so the above limitation or
documentation on a single computer for exclusion may not apply to you. This warranty gives
personal use only and to print copies of you specific legal rights, and you may also have
other rights which vary from state to state.
documentation for personal use provided that
the documentation contains Apple’s copyright
notice.
The Apple logo is a trademark of Apple Inc.
Use of the “keyboard” Apple logo
(Option-Shift-K) for commercial purposes
without the prior written consent of Apple may
constitute trademark infringement and unfair
competition in violation of federal and state
laws.
No licenses, express or implied, are granted
with respect to any of the technology described
in this document. Apple retains all intellectual
property rights associated with the technology
described in this document. This document is
intended to assist application developers to
develop applications only for Apple-labeled
computers.
Every effort has been made to ensure that the
information in this document is accurate. Apple
is not responsible for typographical errors.
Apple Inc.
1 Infinite Loop
Cupertino, CA 95014
408-996-1010
Introduction Introduction 7
3
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C O N T E N T S
4
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
Figures and Listings
5
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
F I G U R E S A N D L I S T I N G S
6
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
I N T R O D U C T I O N
Introduction
Xcode provides an ideal environment in which to develop iPhone applications. The iPhone Reference Library
contains several introductory documents and tutorials to help you learn about this environment. They mostly
teach the paradigms used in the design and implementation of iPhone applications. This document showcases
the tools used to develop iPhone applications.
This document is tailored to people new to iPhone development who want to learn how Xcode streamlines
the development process and get a focused introduction to the main Xcode tools used in iPhone application
development.
To follow the instructions this document provides, you should be familiar with Cocoa-based application
development. See Cocoa Fundamentals Guide for a detailed discussion of the essential concepts you should
be familiar with.
■ “Xcode Quick Tour Overview” (page 9) provides an overview of the main Xcode tools and the project
this document uses to showcase them.
■ “Creating the Project” (page 13) describes how create a iPhone project from a project template.
■ “Implementing the Model Object” (page 15) touches on the design of model objects and their place in
the Model-View-Controller paradigm.
■ “Implementing Controller Objects” (page 19) describes how to write controller objects in Xcode.
■ “Customizing the Application Delegate” (page 21) shows how to add controller-object management in
the application delegate.
■ “Designing the View” (page 23) guides you through the creation of a simple user interface in Interface
Builder.
■ “Connecting the View Controller to the View” (page 35) shows how to connect a view controller to the
view it manages in Interface Builder.
■ “Setting the Application Icon” (page 37) illustrates the process of creating an application icon and adding
it to an iPhone application project.
■ “Running the Application” (page 39) shows how to build and run an application.
Companion Files
To aid you in following the quick tour, the web version of this document contains a downloadable archive
that contains two source files, Calculator.h and Calculator.m. You may use this archive while following
the instructions in “Implementing the Model Object” (page 15).
See Also
■ Xcode Overview describes Xcode and its major components, and provides and overview of the development
process.
■ Your First iPhone Application introduces application development for iPhone.
■ iPhone Application Programming Guide describes the technologies and frameworks used to develop
iPhone applications.
■ iPhone Development Guide describes how to configure computers for iPhone development and explains
how to use Xcode.
■ Interface Builder User Guide provides conceptual information and tasks explaining how to use the Interface
Builder application to design user interfaces.
8 Companion Files
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1
Xcode is the IDE (integrated development environment) used to develop iPhone applications. Xcode comprises
applications, command-line tools, libraries, and other resources that make developing iPhone applications
a gratifying experience.
This chapter provides a short introduction to Xcode. It also provides links to documents that provide details
about the concepts it introduces.
The center of Xcode is the Xcode application. Using this application you create the projects that contain all
the ingredients you need to develop your application. The Xcode application is also your gateway to
community resources such as the iPhone Dev Center, documentation, and mailing lists.
During the various stages of the development process, you focus your attention on different Xcode applications
and tools:
■ Interface Builder. This application lets you design compelling user interfaces graphically. Your work is
saved as nib files that your application loads at runtime. This means that what you design is exactly what
users of your application see; you work with the actual controls that iPhone OS places on the user’s
screen. It also means that you spend less effort writing code for the user-interface–related aspects of
your application.
■ Text editor. Although Xcode reduces the time you spend writing code, you still spend a considerable
part of your development time in the text editor. To that end, the text editor provides many features
with the aim of making your source-code editing a productive and efficient endeavor. Code folding,
code completion, refactoring, and other features allow you to focus your attention on the right areas
and to use your time as efficiently as possible.
■ Debugger. As you start testing your application, you may need to step through your code to determine
the cause of unexpected behavior. The Xcode debugging facilities provide the usual debugging features
such as breakpoints, viewing variables, and so forth, but Xcode provides them right in the text editor.
That is, you can make a change in your code, add a breakpoint, start your application, and perform most
debugging tasks in the same window.
■ Instruments. As you near the end of the development process, you must ensure your application uses
the resources of the device on which it’s running as efficiently as possible, so that battery power is not
wasted and your application does not use system resources unnecessarily. The Instruments application
shows your application’s resource usage, including memory, CPU, and network, in a graphical timeline
that lets you see how your application behaves over time.
The remainder of this document walks you through the development of a very simple application, with the
purpose of showing you some of the Xcode features that make developing iPhone applications an engaging
experience.
This document focuses on the tools rather than the design patterns and conventions of iPhone application
development. However, it’s based on the Model-View-Controller design pattern that pervades iPhone
development, in which an application’s design is separated into data, user interface, and the glue code that
links those two together. For more information on the design patterns used in iPhone application development,
see Cocoa Fundamentals Guide.
This quick tour guides you through the development of the Calc application (shown in Figure 1-1), a very
simple calculator. This document shows you how to:
3. Customize the application delegate to instantiate a view controller and add its view to the application
window.
Further Reading
These documents provide detailed information about the tools introduced earlier:
■ Interface Builder User Guide describes how to use Interface Builder to design user interfaces.
■ “The Text Editor” explores the capabilities of the Xcode text editor.
■ Xcode Debugging Guide describes how to use the Xcode debugger to find and fix execution problems
in your code.
■ Instruments User Guide shows how to use the Instruments application to gather performance metrics
about your application.
Further Reading 11
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 1
Xcode Quick Tour Overview
12 Further Reading
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 2
Xcode provides several iPhone project templates to get you started in your application’s development. The
appropriate template for your needs depends on the type of iPhone application you want to create. This
document uses the Window-Based Application template, which implements a minimal iPhone application
project.
<Xcode> refers to the directory in which you installed the iPhone SDK. Unless you chose a different
directory during the installation process, this directory is /Developer.
3. In the New Project dialog, select Application (under iPhone OS) and choose the Window-Based Application
template.
13
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 2
Creating the Project
■ Calc.app: The application binary, the project’s product. It’s in red because the product hasn’t been
built yet. See "How Files Are Referenced" in Xcode Project Management Guide for details.
■ CalcAppDelegate.h, CalcAppDelegate.m: The files that implement the application’s delegate.
■ MainWindow.xib: The nib file that defines the application’s main window. (Nib files contain an
application’s configured user-interface objects. See Interface Builder User Guide for more information
about nib files.) Despite its name, iPhone applications normally have only one window. This quick tour
shows how to add CalcView.xib, the nib file that defines a view object.
To learn more about the project window, see The Project Window.
14
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 3
Model objects are the data an application uses to populate its user interface. In the Calc application the
model object is a class that implements a calculator. This calculator receives keystrokes as input and provides
a display value the controller object accesses to obtain calculation results. To learn more about model objects,
see The Model-View-Controller Design Pattern.
The source code for the Calculator class is listed in Listing 3-1 and Listing 3-2 (page 16). It’s also included
in this document’s companion files.
/* Calculator.h
*
* Calculator information
*
* Input:
* Digits
* .0123456789
*
* Operators
* +-×/=
*
* Commands:
* D Delete
* C Clear
*/
#import <UIKit/UIKit.h>
- init;
- (void) dealloc;
/**
* Input into the calculator.
*
* Valid characters: .0123456789+-×/=DC
*/
- (void) input:(NSString *) character;
/**
* The calculator’s “display.”
15
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 3
Implementing the Model Object
*/
- (NSString *) displayValue;
@end
/* Calculator.m
*/
#import "Calculator.h"
@implementation Calculator
16
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 3
Implementing the Model Object
[_display appendString:character];
}
}
else if ([Operators rangeOfString:character].length || [character
isEqualToString:(NSString *)Equals]) {
if (!_operator && ![character isEqualToString:(NSString *)Equals]) {
_operand = [[self displayValue] doubleValue];
[self setOperator: character];
}
else {
if (_operator) {
double operand2 = [[self displayValue] doubleValue];
switch ([Operators rangeOfString: _operator].location) {
case 0:
_operand = _operand + operand2;
break;
case 1:
_operand = _operand - operand2;
break;
case 2:
_operand = _operand * operand2;
break;
case 3:
_operand = _operand / operand2;
break;
}
[_display setString: [[NSNumber numberWithDouble: _operand] stringValue]];
}
[self setOperator: ([character isEqualToString:(NSString *)Equals])? nil :
character];
}
last_character_is_operator = YES;
}
else if ([character isEqualToString:(NSString *)Delete]) {
NSInteger index_of_char_to_remove = [_display length] - 1;
if (index_of_char_to_remove >= 0) {
[_display deleteCharactersInRange:NSMakeRange(index_of_char_to_remove, 1)];
last_character_is_operator = NO;
}
}
else if ([character isEqualToString:(NSString *)Clear]) {
if ([_display length]) {
[_display setString:[NSString string]];
}
else {
[self setOperator:nil];
}
}
}
17
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 3
Implementing the Model Object
@end
You can add these source code files to your project in two ways:
■ If you have access to this document’s companion files, add the files to the project:
1. In the Groups & Files list, select Classes.
■ Otherwise, create empty source files and paste the source from the listings:
1. In the Groups & Files list, select Classes.
3. In the New File dialog, choose Cocoa Touch Classes > NSObject subclass.
4. Name the class Calculator and ensure the option to create the header file is selected.
5. Enter the source code in this section into the corresponding files in your project.
Later chapters show how to use the Calculator model class in a controller class, CalcViewController.
18
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 4
Controller objects, the glue objects in the Model-View-Controller paradigm, manage communication between
view objects and model objects. They interpret user-interface interactions in a way that model objects can
understand and present the data the model objects provide in a way that’s easily understood by users. For
more information about controller objects, see The Model-View-Controller Design Pattern.
The CalcViewController object creates an instance of the Calculator class and serves as the intermediary
between the Calculator object and the action messages sent by the controls in the CalcView object (see
“Designing the View” (page 23)).
Add the highlighted lines in Listing 4-1. As you edit the file, note how code completion helps you type
less; to accept its suggestions, press Return. See "Completing Code" in Xcode Workspace Guide for more
information.
#import <UIKit/UIKit.h>
#import "Calculator.h"
To switch from the header file to the corresponding implementation file (CalcViewController.m) in
the editor, choose View > Switch to Header/Source File.
19
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 4
Implementing Controller Objects
#import "CalcViewController.h"
@implementation CalcViewController
- (void)dealloc {
[_calculator release];
[super dealloc];
}
- (IBAction) press:(id)sender {
[_calculator input:[sender titleForState:UIControlStateNormal]];
[displayField setText:[_calculator displayValue]];
}
@end
20
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 5
The application delegate is an object to which the UIApplication object delegates some of its
responsibilities. A delegate allows you to customize or extend the behavior of a class without subclassing it.
For background information about how delegates are used in iPhone application development, see Delegates
and Data Sources.
#import <UIKit/UIKit.h>
@class CalcViewController;
@end
Use the Edit > Select Next Placeholder command (or press Command-/) to move between the arguments
of the initWithNibName:bundle: method when the editor offers that completion.
#import "CalcAppDelegate.h"
#import "CalcViewController.h"
@implementation CalcAppDelegate
@synthesize window;
@synthesize calcViewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
CalcViewController *_calcViewController = [[CalcViewController alloc]
initWithNibName:@"CalcView" bundle:nil];
self.calcViewController = _calcViewController;
21
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 5
Customizing the Application Delegate
- (void)dealloc {
[calcViewController release];
[window release];
[super dealloc];
}
@end
22
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 6
To get users excited about your application, it should have the best user interface possible. The Interface
Builder application allows you to build beautiful, and more importantly, useful user interfaces by dragging
controls from a library of user-interface elements and laying them out in a view as you want them to appear
to the user. Your user-interface designs are known as nib files. Your application loads these resources at
runtime to reconstitute the user interface you designed. This means that you can make substantial changes
to the user interface layout (and even some of its behavior) without having to edit source code. This is the
main benefit of the Model-View-Controller paradigm. See Application Interface Basics for more information.
In this chapter you add the CalcView view object to the Calc application’s main user interface.
Begin by creating the nib file and associating it with the CalcViewController class.
3. Under the iPhone OS platform, select the User Interfaces template group, and choose the View XIB
template.
Figure 6-1 shows the CalcView.xib document window, which contains three proxy objects.
This is how Interface Builder is able to get information about the class from Xcode.
d. Enter CalcViewController in the Class text field. Note that Interface Builder autocompletes
“CalcViewController” because it knows about it through its connection with Xcode. Interface Builder
also adds the press: action method and displayField outlets declared in
CalcViewController.h. Every time you save header files in Xcode, Interface Builder reads them
and updates its proxy objects with the outlets (instance variables) and action methods they declare.
In this section, you create the text field in which the numbers the user enters and the calculation results
appear.
b. In the Organization pane, select Library > Cocoa Touch Plugin > Inputs & Values.
2. Enlarge the text field so that it spans most of the view’s width, as shown in Figure 6-3.
Now you’re ready to add the buttons that implement the calculator’s keypad.
1. Drag a round rect button from the Library to the view, as shown in Figure 6-4.
2. In the Size pane in the inspector, set the button’s width to 64 and its height to 70, as shown in Figure
6-5.
4. To copy the button with its attributes, choose Edit > Duplicate.
Also, replace the buttons’ titles to match the arrangement in the figure.
b. Control-drag from the button to the File’s Owner (the CalcViewController object) in the
CalcView.xib window
c. Release the mouse button and choose the press: event from the menu that appears.
The Button Connections pane in the inspector shows that the button’s Touch Up Inside event sends
the press: message to the File’s Owner.
“Designing the View” (page 23) shows how to connect view objects to a controller object. This chapter shows
how to connect controller objects to view objects in Interface Builder.
To connect CalcViewController to its view and the view’s text field (to display the Calculator instance’s
“screen”):
1. In the CalcView.xib window, select the File’s Owner proxy (which represents an instance of the
CalcViewController class).
2. In the Connections pane in the inspector, connect the displayField outlet to the text field in the view.
35
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 7
Connecting the View Controller to the View
36
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 8
Your application’s icon identifies it among the set of applications a user may have installed on their device.
To that end, your icon should be unique. An application icon file must be a PNG file named icon.png. You
should use a professionally designed icon.
In this chapter, you generate the application icon by taking a snapshot of your main view. However, this is
not the method that you should follow for applications you release to your customers. For details about
generating the application icons users see in iPhone OS, the App Store, and iTunes, see “Application Icon
and Launch Images” in iPhone Application Programming Guide.
To specify your application’s icon in the project, you add an icon.png file to the project and identify that
file in your application’s Info.plist file:
Press Shift-Comand-4 and drag from the top-left corner to the bottom-right corner of the grid.
Mac OS X places the snapshot file in your Desktop using the name Picture 1.png (or a name with a
higher number if you’ve captured other snapshots).
37
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 8
Setting the Application Icon
6. In the dialog that appears, ensure the copy option is selected, and click Add.
8. In the editor window, set the value of the Icon file key to icon.png, as shown in Figure 8-1.
38
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 9
To run the Calc application, you must build it first. In Xcode, choose Build > Build.
If there are no build problems, the project window should look similar to Figure 9-1.
If there are build errors, they are listed in the Errors and Warnings group in the Groups & Files list. The text
editor also shows message bubbles with information about build errors and warnings, as Figure 9-2 shows.
39
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
C H A P T E R 9
Running the Application
If you don’t have a development device connected to your computer, the application runs in iPhone Simulator.
Otherwise, Xcode installs your application on your device and launches it.
iPhone Simulator allows you to run and test iPhone applications even when you don’t have a development
device available. However, the simulator and device environments are different. iPhone Simulator is a Mac
application running on an architecture different from the one present in devices. To learn about the differences
between the two environments, see iPhone Development Guide.
40
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
R E V I S I O N H I S T O R Y
This table describes the changes to Xcode Quick Tour for iPhone OS.
Date Notes
2008-05-28 New document that showcases the tools used to develop iPhone applications.
41
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.
R E V I S I O N H I S T O R Y
Document Revision History
42
2008-10-15 | © 2008 Apple Inc. All Rights Reserved.