IOS Development Guide
IOS Development Guide
2010-07-02
Apple Inc.
2010 Apple Inc.
All rights reserved.
No part of this publication may be reproduced,
stored in a retrieval system, or transmitted, in
any form or by any means, mechanical,
electronic, photocopying, recording, or
otherwise, without prior written permission of
Apple Inc., with the following exceptions: Any
person is hereby authorized to store
documentation on a single computer for
personal use only and to print copies of
documentation for personal use provided that
the documentation contains Apples 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
App Store is a service mark of Apple Inc.
Apple, the Apple logo, Cocoa, Cocoa Touch,
Dashcode, Finder, Instruments, iPhone, iPhoto,
iPod, iPod touch, iTunes, Keychain, Logic, Mac,
Mac OS, Objective-C, Safari, Shake, Spotlight,
and Xcode are trademarks of Apple Inc.,
registered in the United States and other
countries.
iPad is a trademark of Apple Inc.
IOS is a trademark or registered trademark of
Cisco in the U.S. and other countries and is used
under license.
Contents
Introduction
Introduction 9
Organization of This Document 9
Installing the iPhone SDK 10
See Also 10
Chapter 1
Chapter 2
Configuring Applications 25
Editing Property-List Files 25
Managing Application Entitlements 27
Conditionalizing Compilation and Linking 29
Compiling Source Code Conditionally for iOS Applications 29
Linking Frameworks Conditionally for iOS Applications 30
Upgrading a Target from iPhone to iPad 30
Chapter 3
Running Applications 31
Running Sample Applications 31
Specifying the Buildtime Environment 32
Setting the Base SDK 32
Setting Your Code Signing Identity 33
Setting the Architecture 35
Setting the Active Build Configuration 35
Setting the Device Family 35
Specifying the Runtime Environment 36
Specifying Where to Place Your Application 37
3
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
CONTENTS
Chapter 5
Chapter 6
Debugging Applications 55
Debugging Facilities Overview 55
Viewing Console Output and Device Logs 56
Finding Memory Leaks 57
Chapter 7
4
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
CONTENTS
Tuning Applications 71
Chapter 8
Distributing Applications 73
Chapter 9
Appendix A
Appendix B
5
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
CONTENTS
STAssertNoThrow 90
STAssertNoThrowSpecific 91
STAssertNoThrowSpecificNamed 91
STAssertTrueNoThrow 92
STAssertFalseNoThrow 92
Glossary 95
Document Revision History 97
6
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
Chapter 2
Configuring Applications 25
Figure 2-1
Figure 2-2
Figure 2-3
Figure 2-4
Listing 2-1
Listing 2-2
Chapter 3
Chapter 9
Base SDK for All Configurations pop-up menu in the Project Info window 33
Code Signing Identity build setting options 34
A keychain with a developer certificate 34
Base SDK and iPhone Deployment Target build settings 37
The Overview pop-up menu in the Project-window toolbar 38
Viewing an applications iPhone Simulatorbased local file system 41
Downloading an applications device-based local file system 42
Values for the Targeted Device Family build setting 36
Valid App ID/CFBundleIdentifier property pair 39
Invalid App ID/CFBundleIdentifier property pair 39
Chapter 5
Running Applications 31
Figure 3-1
Figure 3-2
Figure 3-3
Figure 3-4
Figure 3-5
Figure 3-6
Figure 3-7
Table 3-1
Table 3-2
Table 3-3
Chapter 4
Project window 13
Using code completion 14
Viewing API reference in the Documentation window 15
Viewing API reference in the Research Assistant 16
Method to draw Hello, World! in a view 22
Distributing Applications 73
Figure 9-1
7
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
Figure 9-2
Listing 9-1
Listing 9-2
Appendix A
main.m 83
HelloWorldAppDelegate.h 83
HelloWorldAppDelegate.m 83
MyView.h 84
MyView.m 84
8
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
INTRODUCTION
Introduction
To develop iOS applications, you use Xcode, Apples first-class integrated development environment (IDE).
Xcode provides all the tools you need to design your applications user interface and write the code that
brings it to life. As you develop your application, you run it on your computer, an iPhone, an iPad, or an iPod
touch.
This document describes the iOS application development process. It also provides information about
becoming a member of the iPhone Developer Program, which is required to run applications on devices for
testing.
After you finish developing your iOS application, you submit it to the App Store, the secure marketplace
where iOS users obtain their applications. However, you should test your application on a small set of users
before publishing it to cover a wide variety of usage patterns and get feedback about your product. This
document describes how to create a group of testers for your application and how to distribute it to them.
To take advantage of this document, you should be familiar with the iOS application architecture, described
in iOS Application Programming Guide. You should also be familiar with basic programming concepts.
After reading this document, youll have a basic understanding of the iOS application development process.
To enhance that knowledge, you should read the documents listed later in this introduction.
Software requirements: This document applies to the iPhone SDK 4.0 (with Xcode 3.2.3) distribution on
Mac OS X v10.6.
If youre interested in developing iOS web applications, visit http://developer.apple.com/safari/library.
"iOS Development Quick Start" (page 11) provides an overview of the major development tasks you
follow to design, build, and run an application using Xcode.
"Configuring Applications" (page 25) describes how to configure your applications properties and
entitlements, and how to adapt it so that it builds correctly in the iOS simulation and device environments.
"Running Applications" (page 31) describes each of the steps required to run or debug your iOS
applications.
"Using iPhone Simulator" (page 43) describes the ways in which you use your computers input devices
to simulate the interaction between iOS users and their devices.
"Managing Devices and Digital Identities" (page 47) shows how to configure your computer and your
device for development; how to use the Xcode Organizer to view console logs or crash information, and
take screen shots of applications running on your device; and how to safeguard the digital identifications
required to install applications in development on devices.
INTRODUCTION
Introduction
"Unit Testing Applications" (page 59) introduces unit testing and describes how you can take advantage
of it in your projects.
"Tuning Applications" (page 71) describes Instruments and Shark, the tools you use to measure and
tune your applications performance.
"Distributing Applications" (page 73) describes how to create an archive of an application using a
distribution provisioning profile, and how to send it to application testers or submit it to iTunes Connect.
It also contains testing instructions for application testers.
"iOS Development FAQ" (page 81) lists common questions developers ask about iPhone Simulator.
"Hello, World! Source Code" (page 83) contains the source code for the Hello, World! application described
in "Tutorial: Hello, World!" (page 17).
"Unit-Test Result Macro Reference" (page 85) describes the test-result macros you can use in your unit-test
methods.
See Also
These documents describe the essential concepts you need to know about developing iOS applications:
10
iOS Application Programming Guide describes the architecture of an iOS application and shows the key
customization points in UIKit and other key system frameworks.
Cocoa Fundamentals Guide introduces the basic concepts, terminology, architectures, and design patterns
of the Cocoa frameworks and development environment.
The Objective-C Programming Language introduces object-oriented programming and describes the main
programming language used for iOS development.
Dashcode User Guide, which describes how to create webpages optimized for Safari on iOS. These web
applications make use of web technologies such as HTML, CSS, and JavaScript.
CHAPTER 1
Developing iOS applications is a pleasant and rewarding endeavor. To convert your ideas into products you
use Xcode, the integrated development environment (IDE) used to develop iOS applications. With Xcode
you organize and edit your source files, view documentation, build your application, debug your code, and
optimize your applications performance.
Note: To develop iOS applications, you must be a registered Apple developer. To run applications on a
device, you must be a member of the iPhone Developer Program. For more information, see "Managing
Devices and Digital Identities" (page 47).
This chapter provides an overview of the major development tasks you follow to design, build, and run an
application using Xcode. It also includes a quick tutorial that shows how to develop the ubiquitous Hello,
World! application for iOS.
2.
3.
Write code.
Xcode provides several features that help you write code fast, including class and data modeling, code
completion, direct access to documentation, and refactoring. See "Editing Code" (page 13) for details.
4.
5.
11
CHAPTER 1
After you have a running application, you should measure its performance to ensure that it uses a devices
resources as efficiently as possible and that it provides adequate responses to the users gestures. See
"Measuring Application Performance" (page 17) for more information.
The rest of this section gives more details about these steps.
Navigation-based Application. An application that presents data hierarchically, using multiple screens.
The Contacts application is an example of a navigation-based application.
OpenGL ES Application. An application that uses an OpenGL ESbased view to present images or
animation.
Split Viewbased Application. An iPad application that displays more than one view onscreen at a time
to, for example, present data in a master-detail or source liststyle arrangement. The iPad Mail application
is an example of a split-viewbased application.
Tab Bar Application. An application that presents a radio interface that lets the user choose from several
screens. The Clock application is an example of a tab bar application.
Utility Application. An application that implements a main view and lets the user access a flip-side view
to perform simple customizations. The Stocks application is an example of a utility application.
View-based Application. An application that uses a single view to implement its user interface.
Window-based Application. This template serves as a starting point for any application, containing an
application delegate and a window. Use this template when you want to implement your own view
hierarchy.
If you need to develop a static library for use in an iOS application, you can add a static library target to your
project by choosing Project > New Target and selecting the Static Library target template in the iPhone
OS/Cocoa Touch list.
Static libraries used in iOS applications do not need to be code signed. Therefore, you should remove the
Code Signing Identity build setting definition from the static library targets you create. To do so:
1.
Open the static-library targets Info window and display the Build pane.
2.
In the Code Signing group, select the Any iPhone OS Device conditional definition for the Code Signing
Identity build setting.
3.
Change the conditional definitions value from iPhone Developer to Dont Code Sign.
To learn more about the iOS application architecture, see iOS Application Programming Guide.
To develop an iOS application, you work on an Xcode project. And you do most of your work on projects
through the project window, which displays and organizes your source files and other resources needed to
build your application. This window allows you to access and edit all the pieces of your project. Figure 1-1
shows the project window.
12
CHAPTER 1
Figure 1-1
Project window
Toolbar
Favorites bar
Status bar
Detail view
The project window contains the following key areas for navigating your project:
Groups & Files list. Provides an outline view of your project contents. You can move files and folders
around and organize your project contents in this list. The current selection in the Groups & Files list
controls the contents displayed in the detail view.
Detail view. Shows the item or items selected in the Groups & Files list. You can browse your projects
contents in the detail view, search them using the search field, or sort them according to column. The
detail view helps you rapidly find and access your projects contents.
Favorites bar. Lets you store and quickly return to commonly accessed locations in your project. The
favorites bar is not displayed by default. To display the favorites bar, choose View > Layout > Show
Favorites Bar.
Status bar. Displays status messages for the project. During an operationsuch as building or
indexingXcode displays a progress indicator in the status bar to show the progress of the current task.
Editing Code
The main tool you use to write your code is the Xcode text editor. This advanced text editor provides several
convenient features:
Header-file lookup. By Commanddouble-clicking a symbol, you can view the header file that declares
the symbol.
13
CHAPTER 1
API reference lookup. By Optiondouble-clicking a symbol, you get access to API reference that provides
information about the symbols usage.
Code completion. As you type code, you can have the editor help out by inserting text for you that
completes the name of the symbol Xcode thinks youre going to enter. Xcode does this in an unobtrusive
and overridable manner.
Code folding. With code folding, you can collapse code that youre not working on and display only the
code that requires your attention.
For details about these and other text editor features, see The Text Editor.
2.
In the Code Completion section of the Code Sense pane, choose Immediate from the Automatically
Suggest pop-up menu.
3.
Click OK.
As you type the name of a symbol, Xcode recognizes that symbol and offers a suggestion, as shown in Figure
1-2. You can accept suggestions by pressing Tab or Return. You may also display a list of completions by
pressing Escape.
Figure 1-2
To learn more about code completion, see Completing Code in Xcode Workspace Guide.
14
CHAPTER 1
Accessing Documentation
During development, you may need fast access to reference for a particular symbol or high-level
documentation about API usage or an iOS technology. Xcode gives you easy access to such resources through
the Research Assistant and the Documentation window.
The Research Assistant is a lightweight window, shown in Figure 1-4 (page 16), that provides a condensed
view of the API reference for the selected item, without taking your focus away from the editor in which the
item is located. This window provides an unobtrusive way to consult API reference. However, when you need
to dig deeper into the reference, the Documentation window is just a click away.
The Documentation window (Figure 1-3) lets you browse and search the developer documentation (which
includes API reference, guides, and articles about particular tools or technologies) installed on your computer.
It provides access to a wider and more detailed view of the documentation than the Research Assistant, for
the times when you need additional help.
Figure 1-3
To display the API reference for a symbol in a source file, you select the symbol in the text editor and choose
Help > Find Selected Text in API Reference (you can also Optiondouble-click the symbol name). This command
searches for the selected symbol in the API reference for your projects SDK and displays it in the
Documentation window. For example, if you select the UIFont class name in a source file and execute the
Find Selected Text in API Reference command, Xcode opens the Documentation window and displays the
API reference for the UIFont class.
15
CHAPTER 1
While the Documentation window is a great tool to browse the iOS documentation library, sometimes you
may not want to take your focus away from the text editor while you write code, but need basic information
about a symbol in a condensed way. The Research Assistant provides such information in a small and
unobtrusive window.
The Research Assistant actively follows you as you move the cursor around a source file. When it recognizes
a symbol for which it finds API reference, the Research Assistant displays that reference, as shown in Figure
1-4. All you have to do is glance at the Research Assistant to get essential details about the symbol.
To display the Research Assistant, choose Help > Show Research Assistant.
Figure 1-4
From the Research Assistant you can quickly jump to more comprehensive reference for the symbol, or even
view the header that declares it.
For more information about accessing documentation in Xcode, see Documentation Access.
16
CHAPTER 1
To compile and debug your code, Xcode relies on open-source tools, such as GCC and GDB. Xcode also
supports team-based development with source control systems, such as Subversion, CVS, and Perforce.
Building your application involves the following steps:
Xcode performs these tasks for you when you execute the Build command. See "Running Applications" (page
31) for details.
Further Exploration
To learn more about the Xcode development process, see A Tour of Xcode.
17
CHAPTER 1
<Xcode> represents the directory in which you installed the Xcode toolset. See Xcode Installation
3.
Select the Window-Based Application template, choose iPhone from the Product pop-up menu, and
click Choose.
4.
Name the project HelloWorld and choose a location for it in your file system.
5.
18
CHAPTER 1
6.
b.
Select the Cocoa Touch UIView subclass template and click Next.
c.
d.
Choose the active SDK for your project and the destination for the application.
To set the active SDK:
a.
19
CHAPTER 1
b.
Choose the SDK from the Base SDK for All Configurations pop-up menu.
Note: If you have a development device plugged in, Xcode chooses the latest iPhone Device SDK for
you. Otherwise, Xcode chooses the latest iPhone Simulator SDK.
To use an iPhone Device SDK you must be a member of the iPhone Developer Program. For more
information, see "Becoming a Member of the iPhone Developer Program" (page 47).
The product destination specifies the type of environment for which Xcode builds your application and
where to install it. If you have a development device plugged in at the time you create the project, Xcode
sets the product destination to Device. Otherwise, it sets the destination to Simulator.
To set the product destination, choose between Device and Simulator from the Overview toolbar menu
in the project window. If you have more than one device connected, specify the device onto which to
install your application by choosing it from the Active Executable section of the Overview toolbar menu.
20
CHAPTER 1
2.
3.
Add the following code line below the existing #import line.
#import "MyView.h"
b.
After making these changes, the code in the HelloWorldAppDelegate.m file should look similar to this:
#import "HelloWorldAppDelegate.h"
#import "MyView.h"
@implementation HelloWorldAppDelegate
@synthesize window;
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch
MyView *view = [[MyView alloc] initWithFrame:[window frame]];
[window addSubview:view];
[view release];
[window makeKeyAndVisible];
return YES;
}
- (void)dealloc {
[window release];
[super dealloc];
}
@end
21
CHAPTER 1
Listing 1-1 shows the code that draws Hello, World! in the window. Add the highlighted code lines to the
drawRect: method in the MyView.m file.
Listing 1-1
If you turned on code completion (as described in "Using Code Completion" (page 14)), as you type symbol
names the text editor suggests completions for the symbol names it recognizes. For example, as you type
CGPointM, the text editor suggests the completion shown in Figure 1-2 (page 14). You can take advantage
of completion here by accepting the suggested completion and jumping to the parameter placeholders:
1.
Jump to the first parameter by choosing Edit > Select Next Placeholder, and type 10.
The Select Next Placeholder command moves you among the arguments in function or method calls
that the text editor suggests as completions to the text youre typing.
2.
3.
Enter the semicolon (;) at the end of the line and press Return.
22
CHAPTER 1
2 errors
<project_directory>/Classes/HelloWorldAppDelegate.m (2 errors)
'MyView' undeclared (first use in this function)
'view' undeclared (first use in this function)
Further Exploration
Now that you learned how to write the standard Hello, World! application for iOS, you can experiment with
HelloWorld, the Cocoa Touch version of this ubiquitous application.
For a step-by-step tutorial in developing a more complex application, see Your First iOS Application.
To learn more about Objective-C, see Learning Objective-C: A Primer.
To learn more about developing iOS applications, see iOS Application Programming Guide.
23
CHAPTER 1
24
CHAPTER 2
Configuring Applications
This chapter describes how to set up your applications properties to customize its runtime environment,
configure its entitlements to take advantage of iOS security features, and how to adapt its build process for
different SDKs and architectures.
This chapter also shows how to upgrade a target that builds an iPhone application into either a target that
builds an application optimized for iPhone and iPad, or two targets, one to build an iPhone application and
one to build an iPad application.
To learn how to set up a device for development, see "Managing Devices and Digital Identities" (page 47).
Information-property list. These files, commonly referred to as info-plist files, contain essential information
used by your application and iOS. See The Information Property List in iOS Application Programming
Guide for information about the application properties defined in info-plist files.
Entitlements. These files define properties that provide your application access to iOS features (such as
push notifications) and secure data (such as the users keychain).
To learn more about property-list files, see Property List Programming Guide.
To edit a property-list file, perform one of these actions:
To edit it in the editor pane of the Project window, select the file in the Groups & Files list or in the detail
view.
To edit it in a dedicated editor window, double-click the file in the Groups & Files list or in the detail
view.
For more information about the Groups & Files list, see Project Window Components in Xcode Workspace
Guide.
Figure 2-1 shows a property-list editor window with an info-plist file.
25
CHAPTER 2
Configuring Applications
Figure 2-1
Each row in the file specifies a property definition (or key/value pair). Key cells specify property names (and
their data types). Value cells specify property values.
These are the property-list editing actions you can perform with the property-list editor:
Add a sibling property. With a row selected and its disclosure triangle closed, click the Add Sibling
button (shown in Figure 2-2) or press Return to add a sibling to the property.
Figure 2-2
After adding the sibling, choose the property type from the property-type menu in the key cell, as shown
in Figure 2-3.
26
CHAPTER 2
Configuring Applications
Figure 2-3
Add a child property. With a row with a multi-value propertya property whose value is a list of
valuesselected and its disclosure triangle open, click the Add Child button (shown in Figure 2-4) or
press Return to add a child to the property.
Figure 2-4
Delete property. With a row selected, press Delete to delete the row.
To make editing property-list files convenient and to ensure the files structure is correct, the property-list
editor uses property-listfile schemas to display property names in the Key column, and formatted values
(such as check boxes for Boolean values) in the Value column. However, you may want to see the properties
key names and values in their XML (or raw) form. To toggle between viewing the formatted keys and values
and their raw form, toggle the Show Raw Keys/Values option of the property-list editor shortcut menu.
27
CHAPTER 2
Configuring Applications
2.
3.
4.
Name the file Entitlements.plist. (You can use any name; just ensure it matches the value of the
Code Signing Entitlements build setting, as explained later in this section.)
5.
6.
Click the Add Child or Add Sibling buttons to the right of the selected row. The Add Child button
has three lines depicting a hierarchy, the Add Sibling button has a plus (+) sign on it.
b.
Choose the entitlement property from the pop-up menu that appears.
If the entitlement you need to add doesnt appear in the menu, choose View > Property List Type
> Default for File Type. Then enter the entitlement-key name and type.
c.
28
CHAPTER 2
Configuring Applications
7.
Set the Code Signing Entitlements build setting for the target to the name of the newly added entitlements
property-list file.
Listing 2-2 shows how to use the TARGET_OS_IPHONE macro in a source to be shared between Mac OS X
and iOS.
29
CHAPTER 2
Configuring Applications
Listing 2-2
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#else
#import <Cocoa/Cocoa.h>
#endif
30
CHAPTER 3
Running Applications
When youre ready to run or debug your application, you build it using the Xcode build system. If there are
no build errors, you can run it in iPhone Simulator or on a device.
Note: After testing your application in iPhone Simulator, you must test it on an iOS-based device to measure
and tune its performance. To be able to run your application on a device, you must be a member of the
iPhone Developer Program; see "Becoming a Member of the iPhone Developer Program" (page 47) for details.
The iPhone SDK comprises two SDK families: The iPhone Simulator SDK and the iPhone Device SDK.
iPhone Simulator SDK: These SDKs build applications that run in iPhone Simulator.
iPhone Device SDK: These SDKs build applications that run in a device.
2.
3.
4.
5.
6.
This chapter describes each of the steps required to run or debug your application. Start with "Running
Sample Applications" (page 31) if youre interested in seeing applications that showcase iOS features.
Download the ZIP archive (the file with the .zip suffix) containing the sample code you want to use.
The archive is named after the application name; for example, HelloWorld.zip.
31
CHAPTER 3
Running Applications
2.
If you download the sample-code projects from the Xcode Documentation window, Xcode expands the
archive and opens the project automatically. Otherwise, continue to the next step.
3.
4.
Navigate to the sample-code project directory, also named after the example application; for example,
HelloWorld.
5.
Double-click the project package, a file with the .xcodeproj suffix. For example,
HelloWorld.xcodeproj. This action opens the project in Xcode.
Troubleshooting: Xcode doesnt launch: If Xcode doesnt launch, you need to download it and install
it on your computer. To download Xcode, visit iPhone Dev Center.
With the sample-code project open in Xcode, follow the instructions in the following sections to build and
run the application.
32
CHAPTER 3
Running Applications
Figure 3-1
Base SDK for All Configurations pop-up menu in the Project Info window
Important: In addition, applications built using a particular version of an SDKsuch as iPhone SDK 3.2, which
targets iOS 3.2may not run reliably on versions of the OS (on the iPhone Simulator or a device) that are
earlier than its corresponding SDK. That is, if you want to run your application on iOS 3.1.3, for example, you
must build it using iPhone SDK 3.1.3.
33
CHAPTER 3
Running Applications
Figure 3-2
Figure 3-3
These are the possible values for the Code Signing Identity build setting:
34
Dont Code Sign. Choose this option if you dont want to sign your binary. Note that with this value,
when you build your applications using the iPhone Device SDK the build fails.
Automatic Profile Selectors. These choices look for an identity whose name starts with iPhone Developer
or iPhone Distribution.
A code signing identity. A specific code signing identity. The code signing identities in your default
keychain are listed under the name of the provisioning profile under which you downloaded them from
the iPhone Provisioning Portal. Expired or otherwise invalid identities are dimmed and cannot be chosen.
CHAPTER 3
Running Applications
Xcode project templates are configured to use the iPhone Developer automatic selector.
Important: If need to use different code signing identities with the same name, you must use a separate
Mac OS X user account for each identity.
Standard. Produces an application binary with a common architecture, compatible with all supported
iOS devices. This option generates the smallest application, but it may not be optimized to run at the
best possible speed for all devices.
Optimized. Produces an application binary optimized for each supported iOS device. However, the build
time is longer than when using the Standard option, and the application is also larger because multiple
instruction sets are bundled into it.
Choose the value for the Architecture build setting in the Build pane of the Target or Project Info window.
If you need to build your application so that it contains executable code for a different set of architectures
than these predefined values offer, you can choose Other from the Architecture build-setting value list and
enter the desired iOS-device architecture names.
To learn more about the Release and Debug configurations, see Building Products.
35
CHAPTER 3
Running Applications
To specify the device families on which you want your application to be able to run:
1.
2.
In the Build pane, locate the Targeted Device Family build setting and choose an appropriate value for
it.
Table 3-1 lists the values you can specify for the Targeted Device Family build setting. It also indicates the
device family the built application is optimized for.
Table 3-1
Value
iPhone
iPad
iPad
36
Target the latest iOS release. Targeting the latest release allows you to take advantage of all the features
available in the latest version of iOS. However, this approach may offer a smaller set of users capable of
installing your application on their devices because your application cannot run on iOS releases that are
earlier than the target release.
Target an earlier iOS release. Targeting an earlier release lets you publish your application to a larger
set of users (because your application runs on the target OS release and later releases), but may limit
the iOS features your application can use.
CHAPTER 3
Running Applications
You specify the earliest iOS release on which you want your application to run with the iPhone OS Deployment
Target build setting. By default, this build setting is set to the iOS release that corresponds to the Base SDK
build-setting value. For example, when you set Base SDK to iPhone Device 2.2.1 or iPhone Simulator 2.2.1,
the value of the iPhone Deployment Target build setting is iPhone OS 2.2.1, as shown in Figure 3-4.
Figure 3-4
To build your application using the iPhone Device 3.0 SDK and to allow it to run on iOS 2.2.1, set Base SDK
to iPhone Device 3.0 and iPhone Deployment Target to iPhone OS 2.2.1.
When you build your application, your deployment target selection is reflected in the MinimumOSVersion
entry in the applications Info.plist file. When you publish your application to the App Store, the store
indicates the iOS release on which your application can run based on the value of this property.
iPhone Device SDK: If the iPhone Device SDK release is earlier than the applications target iOS release (for
example, the active SDK is iPhone Device 2.2.1 and iPhone Deployment Target is iPhone OS 3.0), Xcode
displays build warnings when it detects that your application is using a feature thats not available in the
target OS release. See "Specifying the Runtime Environment" (page 36) for more information.
You must also ensure that the symbols you use are available in the applications runtime environment using
SDK-compatibility development techniques. These techniques are described in SDK Compatibility Guide.
iPhone Simulator SDK: When using the iPhone Simulator SDK to test your application, the iPhone Simulator
software version must be set to the iOS release that corresponds to the iPhone Simulator SDK used to build
the application. For example, if you build your application using iPhone Simulator SDK 2.2.1, you must set
the iPhone Simulator software version to iOS 2.2.1. See "Specifying Where to Place Your Application" (page
37) for details.
Choose whether you want to run your application on a device or in the simulation environment.
37
CHAPTER 3
Running Applications
The first two options in the Overview toolbar menu let you choose between these alternatives.
2.
Choose the device or the iPhone Simulator version on which you want to run the application.
The Active Executable section of the Overview toolbar menu lets you specify a device or iPhone Simulator
version.
Figure 3-5
38
CHAPTER 3
Running Applications
To solve the error, choose a valid code signing identity, as described in "Setting Your Code Signing
Identity" (page 33).
Application ID Errors
Application ID build errors may be produced due to a conflict between the application ID set in your
provisioning profile (obtained through the Program Portal) and the application ID specified by the
CFBundleIdentifier property of your application. To avoid such errors, ensure that the application ID in
the profile is set to com.<organization_name>.* and your applications CFBundleIdentifier property
is set to com.<organization_name>.<application_name>. That is, if the application ID in your
provisioning profile specifies a domain set, the application ID specified by the CFBundleIdentifier property
of your application must not redefine the domain set, it may only reduce it. Table 3-2 and Table 3-3 identify
valid and invalid pairing of these items.
Table 3-2
com.mycompany.*
CFBundleIdentifier com.mycompany.MyApp
com.mycompany.MyApp.*
CFBundleIdentifier com.mycompany.MyApp
To learn about the structure of iOS application binaries, including details about the CFBundleIdentifier
property, see The Application Bundle in iOS Application Programming Guide.
To learn about solving other build errors, use the techniques described in Viewing Errors and Warnings in
Xcode Project Management Guide to fix them.
39
CHAPTER 3
Running Applications
40
CHAPTER 3
Running Applications
Figure 3-6
2.
3.
In the Summary pane, click the disclosure triangle next to your application.
4.
Click the download button (the down-pointing arrow to the left of the Application Data package), as
shown in Figure 3-7.
5.
In the dialog that appears, choose a location for the file-system copy.
41
CHAPTER 3
Running Applications
Figure 3-7
2.
3.
Drag the backup to your application in the Summary pane of the Organizer.
Further Exploration
To learn more about using Xcode to build and run applications, see Xcode Project Management Guide.
42
Further Exploration
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
CHAPTER 4
The iOS simulation environment lets you build and run your iPhone or iPad application on your computer.
You use the simulation environment to:
Find and fix major problems in your application during design and early testing.
Learn about the Xcode development experience and the iOS development environment before becoming
a member of the iPhone Developer Program.
Measure your applications memory usage before carrying out detailed performance analysis on iOS-based
devices.
A major part of the iOS simulation environment is the iPhone Simulator application. This application presents
the iPhone or iPad user interface in a window on your computer. The application provides several ways of
interacting with it using your keyboard and mouse to simulate taps and device rotation, among other gestures.
Important: iOS 4.0 uses the same Objective-C runtime as Mac OS X v10.6. iOS 3.2 and earlier use the Mac
OS X v10.5 Objective-C runtime. Because of this change, binaries generated with an iPhone SDK distribution
earlier than 4.0 do not run in the simulator thats part of the iPhone SDK 4.0 and later distributions. After
moving from iPhone SDK 3.2 and earlier distributions to a 4.0 or later distribution, you must rebuild your
iPhone Simulator binaries to run them in the simulator. If you use licensed static libraries in your application,
you must obtain versions of them generated with an iPhone SDK 4.0 or later distribution. For more information
about the Objective-C runtime, see Objective-C Runtime Reference.
The following sections describe the ways in which you use your computers input devices to simulate the
interaction between users and their devices. They also show how to uninstall applications from the simulator
and how to reset the contents of the simulator.
43
CHAPTER 4
Simulate Memory Warning. Sends the frontmost application low-memory warnings. For information
on how to handle low-memory situations, see Observing Low-Memory Warnings in iOS Application
Programming Guide.
Toggle In-Call Status Bar. Toggles the status bar between its normal state and its in-call state. The status
bar is taller in its in-call state than in its normal state. This command shows how your applications user
interface looks when the user launches your application while a phone call is in progress.
Simulate Hardware Keyboard. Toggles the software keyboard on iPad simulation. Turn off the software
keyboard to simulate using a keyboard dock or wireless keyboard with an iPad device.
Performing Gestures
Table 4-1 lists gestures you can perform on the simulator (see iPhone Human Interface Guidelines for gesture
information).
Table 4-1
Gesture
Desktop action
Tap
Click.
Double click.
Swipe
Flick
44
CHAPTER 4
Gesture
Desktop action
Drag
Pinch
Installing Applications
Xcode installs applications in iPhone Simulator automatically when you build your application using the
iPhone Simulator SDK. See "Running Applications" (page 31) for details.
In iPhone Simulator, you can install only applications that you build using the iPhone Simulator SDK. You
cannot install applications from the App Store in the simulator.
Uninstalling Applications
To uninstall applications you have installed on the simulator use the same method used to uninstall
applications from devices:
1.
Place the pointer over the icon of the application you want to uninstall and hold down the mouse button
until the icon starts to wiggle.
2.
3.
Installing Applications
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
45
CHAPTER 4
The User domain comprises all user data iOS stores including third-party application binaries, system databases
(such as the Address Book and Calendar databases), application preferences, and so on. This location is also
known as <iOSUserDomain>.
iPhone Simulator stores system application preferences files in <iOSUserDomain>/Library/Preferences.
Third-partyapplication preferences files are stored in
<iOSUserDomain>/Applications/<app_UUID>Library/Preferences.
46
CHAPTER 5
With iPhone Simulator you can start developing iOS applications without using iOS-based devices. This way
you can familiarize yourself with the API and development workflows used to develop applications. However,
you must always test your applications on actual devices before publishing them to ensure that they run as
intended and to tune them for performance on actual hardware.
As a registered Apple developer you can log in to the iPhone Dev Center, which provides access to iOS
developer documentation and lets you build iOS applications that run in iPhone Simulator. (To become a
registered Apple developer, visit http://developer.apple.com/programs/register/.) Being a registered Apple
developer, however, doesnt allow you to run applications on iOS-based devices. To do so you must be a
member of the iPhone Developer Program. See "Becoming a Member of the iPhone Developer Program" (page
47) for more information.
This chapter shows how to configure your computer and devices for iOS development. It also shows how to
view your applications console logs or crash information, or to take screenshots of your application as it
runs. The chapter also describes how to safeguard the digital identifications required to install applications
in development in devices.
47
CHAPTER 5
Note: Configuring an iOS-based device for development does not hinder its normal operation.
In preparing your device for development, you create or obtain the following digital assets:
Certificate signing request. A certificate signing request (CSR) contains personal information used to
generate your development certificate. You submit this request to the iPhone Provisioning Portal.
Development certificate. A development certificate identifies an iOS application developer. After the
CSR is approved, you download your developer certificate from the portal and add it to your keychain.
When you build your iOS application with Xcode, it looks for your development certificate in your
keychain; if it finds the certificate, Xcode signs your application, otherwise, it reports a build error.
Provisioning profile. A provisioning profile associates one or more development certificates, devices,
and an app ID (iOS application ID).
To be able to install iOS applications signed with your development certificate on a device, you must
install at least one provisioning profile on the device. This provisioning profile must identify you (through
your development certificate) and your device (by listing its unique device identifier). If youre part of
an iOS developer team, other members of your team, with appropriately defined provisioning profiles,
may run applications you build on their devices.
Computer
Certificate Signing Request
Keychain
Xcode Organizer
Development Certificate
(is stored on computer)
Digital identity
Public key
Provisioning Profile
(is stored on device)
Development certificates
Device identifiers
App ID
48
CHAPTER 5
1.
Creating a provisioning profile that identifies your device on the iPhone Provisioning Portal.
2.
You can have Xcode perform these tasks automatically when you designate new devices for development,
as described in "Provisioning a Device for Generic Development" (page 49). However, if your application
requires a specialized provisioning profile (if it uses push notifications or in-app purchases), you need to
follow the steps in "Provisioning a Device for Specialized Development" (page 51).
2.
3.
4.
49
CHAPTER 5
5.
In the DEVICES group, select your device and click Use for Development.
6.
In the dialog that appears, enter your iPhone Developer Program credentials.
Xcode logs in to the Portal and adds the new device to it. Xcode also adds a provisioning profile called
Team Provisioning Profile: * to your device. This provisioning profile is shared among the members of
your team who provision their devices automatically.
50
CHAPTER 5
7.
If Xcode offers to request a development certificate in your behalf, click Submit Request.
To ensure that your device is provisioned correctly, you can download a sample project, build it using a
device SDK, and run the application it produces on your device. See, "Running Sample Applications" (page
31) for details.
2.
In the Xcode Organizer, select Provisioning Profiles in the IPHONE DEVELOPMENT group.
If you dont see the provisioning profile you want to add to your device in the provisioning profile list,
click Refresh.
3.
Drag the specialized provisioning profile to your device in the DEVICES group.
51
CHAPTER 5
Installing iOS
When you develop applications using the iPhone SDK, you should test those applications on devices running
the iOS version the SDK targets. You can download the latest release of the iPhone SDK from the iPhone Dev
Center. Use iTunes to install the latest iOS release onto your device.
Note: During seed periods, you can download seed releases of the iPhone SDK and iOS from the iPhone
Dev Center.
To restore a device:
1.
2.
3.
4.
From the Software Version pop-up menu, choose the version of iOS you want to place on the device.
If youre using a seed release of the iPhone SDK and the version of iOS you want to install is not listed
in the Software Version pop-up menu:
a.
Download the iOS seed that corresponds to your iPhone SDK seed from http://developer.apple.com.
Important: You must be a member of the iPhone Developer Program to be able to download iOS.
b.
c.
Navigate to the disk image containing the iOS developer software and click Open.
Xcode extracts the iOS software from the disk image. You can dispose of the disk image you
downloaded.
d.
From the Software Version pop-up menu, choose the newly downloaded iOS version.
6.
52
Installing iOS
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
CHAPTER 5
You tell Xcode that you want to build your application for a device and that you want to run it on a connected
device by setting the active SDK to an iPhone Device SDK. See "Building Your Application" (page 38) for
details.
2.
Open the Organizer window, select your device, and click Screenshots.
3.
Click Capture.
To make that screen shot your applications default image, click Save As Default Image.
To get a PNG file of the screenshot, drag it to the desktop.
If you have iPhoto installed on your computer, you may capture screen shots directly on your device and
import them into your iPhoto library.
To capture a screen shot on your device, press the the Lock and Home buttons simultaneously. Your screen
shot is saved in the Saved Photos album in the Photos application.
Note: Although the default image includes the status bar as it looked when the screen shot was captured,
iOS replaces it with the current status bar when your application launches.
2.
53
CHAPTER 5
3.
4.
Name the file, select a location for it, enter a password to secure the file, and click Save.
Now, when you need to develop iOS applications on another computer, import your digital-identification
items into it by performing these steps:
54
1.
2.
3.
4.
5.
6.
Locate the archive, enter the password used to secure it, and click Open.
CHAPTER 6
Debugging Applications
The text editor. The text editor allows you to debug your code right in your code. It provides most of
the debugging features you need. You can:
View the value of variables by hovering the mouse pointer over them
Debugger strip
Gutter
Debugger datatip
55
CHAPTER 6
Debugging Applications
The Debugger window. When you need to perform more focused debugging, the Debugger window
provides all the debugging features the text editor provides using a traditional interface. This window
provides lists that allow you to see your call stack and the variables in scope at a glance.
Toolbar
Variable list
Thread list
Text editor
Status bar
The GDB console. A GDB console window is available for text-based debugging.
Important: To debug successfully on a device, you must install on your computer the iPhone SDK
corresponding to the iOS release installed on the device. That is, you cannot debug an application on a device
running iOS 2.2.1 if you do not have the iPhone 2.2.1 SDK installed on your computer.
For more information about the Xcode debugging facilities, see Xcode Debugging Guide.
56
1.
2.
CHAPTER 6
Debugging Applications
3.
Click Console.
You can save the console output to a file by clicking Save Console As.
The Device Logs pane in the Organizer contains information about application crashes. You may have to
unplug your device and plug it in again to refresh the crash list.
For more information about crash logs, see Understanding and Analyzing iPhone OS Application Crash Reports.
Choose Project > Edit Active Executable to open the executable Info window.
57
CHAPTER 6
Debugging Applications
2.
Click Arguments.
3.
Click the add (+) button in the Variables to be set in the environment section.
4.
Enter NSZombieEnabled in the Name column and YES in the Value column.
5.
Make sure that the checkmark for the NSZombieEnabled entry is selected.
For more information about configuring executable environments, see Configuring Executable Environments
in Xcode Project Management Guide.
iPhone 3.1 SDK introduces the Leaks instrument, which you can use in the Instruments application to easily
find memory leaks. For more information, see Instruments User Guide.
58
CHAPTER 7
Unit tests help you write robust and secure code. Xcode provides an easy-to-use flexible unit-testing
environment that you can use to ensure your code works as designed as it goes through changes.
Software requirements: This feature is available in iPhone SDK 3.0 and later.
This chapter introduces unit testing and describes how you can take advantage of it in your projects.
For a case study in unit-testing adoption and usage, see:
http://www.macdevcenter.com/pub/a/mac/2004/04/23/ocunit.html
Xcode is already configured for unit testing. You dont need to install additional software.
Logic tests. These tests check the correct functionality of your code in a clean-room environment; that
is, your code is not run inside an application. Logic tests let you put together very specific test cases to
exercise your code at a very granular level (a single method in class) or as part of a workflow (several
methods in one or more classes). You can use logic tests to perform stress-testing of your code to ensure
59
CHAPTER 7
that it behaves correctly in extreme situations that are unlikely in a running application. These tests help
you produce robust code that works correctly when used in ways that you did not anticipate. Logic tests
are iPhone Simulator SDK-based; however, the application is not run in iPhone Simulator: The code being
tested is run during the corresponding targets build phase.
Application tests. These tests check the functionality of your code in a running application. You can use
application tests to ensure that the connections of your user-interface controls (outlets and actions)
remain in place, and that your controls and controller objects work correctly with your object model as
you work on your application. Because application tests run only on a device, you can also use these
tests to perform hardware testing, such as getting the location of the device.
Setting Up Testing
Logic unit tests (introduced in "Unit Testing Overview" (page 59)) allow you to perform exhaustive, highly
tailored testing of your code. To perform logic tests, you build a unit-test bundle using the iPhone Simulator
SDK. When you build the unit-test bundle, Xcode runs the test suites that are part of the bundle. You
incorporate test suites into a test bundle by adding SenTestCase subclasses to the bundle. These classes
contain test-case methods that call the API to exercise and report whether the calls produced the expected
results. Xcode reports whether the tests passed or failed in text editor windows and the Build Results window.
Application unit tests let you test your code within an application running on an iOS device, with access to
the resources available in the Cocoa Touch framework.
This section describes how to set up a project for each type of unit test.
Add an iPhone OS unit-test bundle target to the project. Name the target LogicTests (you can use any
name you like for your unit-test bundles, but you should include the suffix Tests to identify them as such).
For details about adding targets to a project, see Creating Targets in Xcode Build System Guide.
60
2.
3.
Add a group called Tests to the Group & Files list, and select that group in the list.
4.
Add a unit-test class to the unit-test-bundle target. Each unit-test class in the bundle makes up a test
suite.
a.
Choose File > New, select the iPhone OS unit-test class template, and click Next.
b.
Name the class LogicTests (you can use any name here, too).
c.
Setting Up Testing
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
CHAPTER 7
d.
5.
Ensure that LogicTests is the only target selected in the target list.
6.
7.
Set the base SDK for the project to iPhone Simulator 3.0 or later.
For more information about the Base SDK build setting, see "Setting the Base SDK" (page 32).
Setting Up Testing
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
61
CHAPTER 7
8.
Set the active target to LogicTests and choose Build > Build. If the unit-test bundle is configured correctly,
the build fails and Xcode displays an error message in the text editor.
9.
Now make the test case pass by changing the highlighted lines in LogicTest.m:
#import "LogicTests.h"
@implementation LogicTests
- (void) testPass {
STAssertTrue(TRUE, @"");
}
@end
At this point you have a correctly configured logicunit-test bundle. See "Writing Tests" (page 67) to learn
how to add test cases to it.
Make a copy of the target that builds the application to test by choosing Duplicate from its shortcut
menu, and name it <application_name>Testing (for example, MyAppTesting). (You can use any
name for this target, but you should include the suffix Testing to identify it as a target used to run
application unit tests.) The only purpose of this target is to run application unit tests.
2.
Add an iPhone OS unit-test bundle target to the project. Name the target <application_name>Tests
(for example, MyAppTests).
For details about adding targets to a project, see Creating Targets in Xcode Build System Guide.
62
Setting Up Testing
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
CHAPTER 7
3.
Make the MyAppTesting target dependent on the MyAppTests target by dragging MyAppTests to
MyAppTesting.
Making the MyAppTesting target dependent on the MyAppTests target ensures that when you build
MyAppTesting, MyAppTests gets built first (if you have modified MyAppTests since it was last built).
Setting Up Testing
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
63
CHAPTER 7
64
4.
Embed the MyAppTests bundle into the MyAppTesting bundle by dragging the MyAppTests.octest
product to the MyAppTesting target Copy Bundle Resources build phase.
5.
Add a group called Tests to the Groups & Files list (if it doesnt already exist), and select that group in
the list.
6.
Add a unit-test class to the MyAppTests target. Each unit-test class in the bundle makes up a test suite.
a.
Choose File > New, select the iPhone OS unit-test class template, and click Next.
b.
Name the class MyAppTests (you can use any name for this class, but it should have the suffix Tests
for easy identification).
c.
Setting Up Testing
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
CHAPTER 7
d.
7.
Ensure that MyAppTests is the only target selected in the target list.
8.
9.
Set the Base SDK for the project to iPhone Device 3.0 or later.
For more information about the Base SDK build setting, see "Setting the Base SDK" (page 32).
Setting Up Testing
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
65
CHAPTER 7
10. Set the active target to MyAppTesting and choose Build > Build and Run. Xcode builds your application,
installs and launches it on your device, and runs the test suite, which fails. You can see the test results
in the console. This outcome confirms that application unit testing is set up correctly.
11. Now make the test suite pass by changing the highlighted lines in MyAppTests.m:
#import "MyAppTests.h"
@implementation LogicTests
- (void) testAppDelegate {
id app_delegate = [[UIApplication sharedApplication] delegate];
STAssertNotNil(app_delegate, @"Cannot find the application delegate.");
}
@end
66
Setting Up Testing
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
CHAPTER 7
Now that you have a correctly configured application unit-test bundle, see "Writing Tests" (page 67) to learn
how to add test cases to it.
Writing Tests
After configuring a unit-test bundle with a unit-test class (which implements a test suite), you add cases to
the suite by adding test-case methods to the class. A test-case method is an instance method of a unit-test
class thats named test..., with no parameters, and whose return type is void. Test-case methods call the
API they test and report whether the API performed as expectedfor example, whether it returns the
anticipated return or whether it raises an exception. Test-case methods use a set of macros to check for the
expected conditions and report their findings. "Unit-Test Result Macro Reference" (page 85) describes these
macros.
For a test case to access the subject API, you may have to add the appropriate implementation files to the
unit-test bundle and import the corresponding header files into your unit-test class. For an example of a
project that uses unit tests, see the iPhoneUnitTests sample-code project.
Note: iPhone unit-testcases are written in Objective-C.
This is the structure a test-case method:
- (void) test<test_case_name> {
...
// Set up, call test-case subject API.
ST...
// Report pass/fail to testing framework.
...
// Tear down.
}
Each test-case method is invoked independently. Therefore, each method must set up and tear down any
auxiliary variables, structures, and objects it needs to interact with the subject API. Conveniently, you can
add a pair of methods to a unit-test class that are called before and after each test-case method is invoked:
setUp and tearDown. Just like test-case methods, the type of both methods is void and they take no
arguments.
This is an example of a setUp/tearDown method pair:
- (void) setUp {
test_subject = [[MyClass new] retain];
STAssertNotNil(test_subject, @"Could not create test subject.");
}
- (void) tearDown {
[test_subject release];
}
Writing Tests
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
67
CHAPTER 7
Note: When theres a reported failure in a setUp or tearDown call, the failure is ultimately reported in the
test-case method that originated the call.
Running Tests
To ensure that changes you make to your code dont modify its correct behavior, you should run your test
suites periodically, especially after making significant changes. This section shows how to run logic and
application tests. It also shows how to set up an application target so that Xcode runs logic tests every time
you build it.
Making the the target active and choosing Build > Build
68
Drag your logic-test target into your application target. This action makes the application target depend
on the logic-test target.
Running Tests
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
CHAPTER 7
When you build the application target, Xcode builds the logic target first, reporting test failures in the
process.
2.
3.
4.
5.
In the Architectures group of the build-setting list, set Base SDK to iPhone Simulator 3.0, and deselect
Build Active Architecture Only.
Define API requirements. You should define requirements and outcomes for each method or function
that you add to your program. These requirements should include input and output ranges, exceptions
thrown and the conditions under which they are raised, and the type of returned values (especially if
they are objects). Specifying requirements and making sure that requirements are met in your code help
you write robust, secure code.
69
CHAPTER 7
See the iPhoneUnitTests sample-code project for an example of using exceptions to identify and report
incorrect API usage by a client.
70
Write test cases as you write code. As you write each API, write one or more test cases that ensure the
APIs requirements are met. Its harder to write unit tests for existing code than for code you havent
written yourself or have written recently.
Check boundary conditions. If the parameter of a method expects values in a specific range, your tests
should pass values that include the lowest and highest values of the range. For example, if an integer
parameter can have values between 0 and 100, inclusive, three variants of your test may pass the values
0, 50, and 100, respectively.
Use negative tests. Negative tests ensure your code responds to error conditions appropriately. Verify
that your code behaves correctly when it receives invalid or unexpected input values. Also verify that it
returns error codes or raises exceptions when it should. For example, if an integer parameter can accept
values in the range 0 to 100, inclusive, you should create test cases that pass the values -1 and 101 to
ensure that the API raises an exception or returns an error code.
Write comprehensive test cases. Comprehensive tests combine different code modules to implement
some of the more complex behavior of your API. While simple, isolated tests provide value, stacked tests
exercise complex behaviors and tend to catch many more problems. These kinds of test mimic the
behavior of your code under more realistic conditions. For example, in addition to adding objects to an
array, you could create the array, add several objects to it, remove a few of them using different methods,
and then ensure the set and number of remaining objects is correct.
Cover your bug fixes with test cases. Whenever you fix a bug, write one or more tests cases that verify
the fix.
CHAPTER 8
Tuning Applications
Optimizing your applications performance is an important phase of the development process, more so in
iOS-based devices, which, although powerful computing devices, do not have the memory or CPU power
that desktop or portable computers possess. You also have to pay attention to your applications battery
use, as it directly impacts your customers battery-life experience.
This chapter describes Instruments and Shark, the tools you use to measure and tune your applications
performance.
Prerequisites: Follow the instructions in "Running Applications" (page 31) before trying the application-tuning
techniques described in this chapter on your application.
For general performance guidelines, see iOS Application Programming Guide.
71
CHAPTER 8
Tuning Applications
Maximum of two fingers. If your applications user interface can respond to touch events involving
more than two fingers, you can test that capability only on devices.
Accelerometer. Although you can access your computers accelerometer (if it has one) through the UIKit
framework, its readings differ from the accelerometer readings on a device. This discrepancy stems
largely from the different positioning of the screen in relation to the rest of the hardware between
computers and iOS-based devices.
OpenGL ES. OpenGL ES uses renderers on devices that are slightly different from those it uses in iPhone
Simulator. For this reason, a scene on the simulator and the same scene on a device may not be identical
at the pixel level. See Drawing with OpenGL ES in iOS Application Programming Guide for details.
Build and run your application on the device as described in "Running Applications" (page 31).
2.
Launch Instruments.
The Instruments application is located at <Xcode>/Applications. (<Xcode> refers to the installation
location of the development tools.)
3.
4.
From the Default Target pop-up menu in the toolbar, select the iOS-based device containing the
application from which you want to collect performance data.
5.
Add or remove instruments from the trace document to collect the desired data.
6.
Use the Default Target pop-up menu, to launch or attach to the target application.
7.
Click Record to start collecting data and use your application, exercising the areas you want to examine.
To learn more about measuring and analyzing application performance, see Instruments User Guide. This
document provides general information about using Instruments.
72
CHAPTER 9
Distributing Applications
When youre ready to distribute your application for testing or for general distribution through the App Store,
you need to create an archive of the application using a distribution provisioning profile, and send it to
application testers or submit it to iTunes Connect. This chapter shows how to perform these tasks.
73
CHAPTER 9
Distributing Applications
Figure 9-1
Developer
Program Portal
Tester device ID
Tester device ID
device
Tester Device
Tester
provisioning profile
Tester
provisioning profile
Tester device
Tester
provisioning profile
Tester
provisioning profile
Test application
Test application
Test app ID
Development
certificate
iTunes
Prerequisites:
Before sending your application to testers, review the information in "Running Applications" (page 31).
To add testers to your team you must have distribution certificate in the Portal.
To help testers obtain the information you need to add them to your testing program and to show them
how to send you crash logs, you can send them the information in "Instructions for Application Testers" (page
77).
Important: To add testers to your team, you must be a member of the iPhone Developer Program. See
"Managing Devices and Digital Identities" (page 47) for details.
The remainder of this chapter describes the steps you need to perform to add testers to your team and shows
how to import the crash logs they send you into the Organizer.
74
CHAPTER 9
Distributing Applications
1.
2.
3.
If you already have a testing provisioning profile for your application in the Portal, add the testers device
IDs to it. Otherwise, create the profile with these characteristics:
Distribution method Ad Hoc
4.
Profile name
App ID
Devices
75
CHAPTER 9
Distributing Applications
Figure 9-2
The iTunes artwork your testers see should be your applications icon. This artwork must be a 512 x 512 JPEG
or PNG file named iTunesArtwork. Note that the file must not have an extension.
After generating the file of your applications icon, follow these steps to add it to your application:
1.
2.
3.
Choose Project > Add to Project, navigate to your iTunesArtwork file, and click Add.
4.
In the dialog that appears, select the Copy items option and click Add.
76
Set the Code Signing Identity build setting to a test provisioning profile.
CHAPTER 9
Distributing Applications
2.
In the Project window Overview toolbar menu, set Active Executable to a device.
3.
Note: To streamline this process, create a distribution configuration (by duplicating the Release configuration),
and change the Code Signing Identity build setting in that configuration. That way, you can keep your
development and distribution configurations separate. For more information about build configurations, see
"Build Configurations".
In the Archived Applications list in the Organizer, select the application archive you want to send to
testers, and click Share Application.
2.
Click E-Mail.
In the email message, provide your testers information they need to test your application.
Launch iTunes.
77
CHAPTER 9
Distributing Applications
2.
3.
4.
In the Summary pane, click the Serial Number label. It changes to Identifier.
5.
6.
Email your device identifier to the developer. Be sure to include your name and device name in the email.
2.
78
1.
2.
3.
Enter ~/Library/Logs/CrashReporter/MobileDevice.
4.
5.
Select the crash logs named after the application youre testing.
6.
7.
In the New Message window, enter the developers email address in the To field and
<application_name> crash logs from <your_name> (for example, MyTestApp crash logs
from Anna Haro) in the Subject field.
8.
CHAPTER 9
Distributing Applications
9.
In the Finder, you may delete the crash logs you sent to avoid sending duplicate reports later.
C:\Users\<user_name>\AppData\Roaming\Apple
computer\Logs\CrashReporter/MobileDevice
Listing 9-2
Open the folder named after your devices name and send the crash logs for the application youre testing
in an email message using the subject-text format <application_name> crash logs from <your_name>
(for example, MyTestApp crash logs from Anna Haro) to the applications developer.
2.
Profile name
App ID
79
CHAPTER 9
Distributing Applications
Set the Code Signing Identity build setting to the distribution profile.
2.
In the Overview toolbar menu in the Project window, set Active Executable to a device.
3.
80
1.
In the Archived Applications list in the Organizer, select the application archive you want to submit, and
click Submit Application to iTunes Connect.
2.
In the dialog that appears, enter your iTunes Connect credentials, and click Submit.
CHAPTER 10
Here are some common questions developers ask about iOS development:
How do I submit applications to iTunes Connect for distribution through the App Store.
Use the Build and Archive command. See "Distributing Applications" (page 73).
Do Objective-C properties need to be backed up by instance variables or accessor methods for them to
work?
Yes.
81
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
CHAPTER 10
82
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
APPENDIX A
This appendix contains the source code for the Hello, World! application described in "Tutorial: Hello,
World!" (page 17).
Listing A-1
main.m
// main.m
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
Listing A-2
HelloWorldAppDelegate.h
// HelloWorldAppDelegate.h
#import <UIKit/UIKit.h>
@interface HelloWorldAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@end
Listing A-3
HelloWorldAppDelegate.m
// HelloWorldAppDelegate.m
#import "HelloWorldAppDelegate.h"
#import "MyView.h"
@implementation HelloWorldAppDelegate
@synthesize window;
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
MyView *view = [[MyView alloc] initWithFrame:[window frame]];
[window addSubview:view];
[view release];
[window makeKeyAndVisible];
return YES;
}
83
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
APPENDIX A
- (void)dealloc {
[window release];
[super dealloc];
}
@end
Listing A-4
MyView.h
// MyView.h
#import <UIKit/UIKit.h>
@interface MyView : UIView {
}
@end
Listing A-5
MyView.m
// MyView.m
#import "MyView.h"
@implementation MyView
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect {
NSString *hello
= @"Hello, World!";
CGPoint location = CGPointMake(10, 20);
UIFont
*font
= [UIFont systemFontOfSize:24];
[[UIColor whiteColor] set];
[hello drawAtPoint:location withFont:font];
}
- (void)dealloc {
[super dealloc];
}
@end
84
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
APPENDIX B
The SenTestingKit framework defines a set of test-case result macros that allow you to report the test-case
results to the framework. When a test fails, the framework emits a test-failure message, which Xcode displays
in text-editor, Build Results, or console windows, depending on the type of unit tests being performed.
The following sections describe the test-result macros you can use in your test-case methods. These macros
are declared in SenTestCase.h.
Important: When the expressions your test cases evaluate throw exceptions, they produce unknown errors.
To test whether your code raises exceptions, create test cases that explicitly check for the presence or absence
or exceptions; see "Exception Tests" (page 89).
Unconditional Failure
STFail
Fails the test case.
STFail(failure_description, ...)
Parameters
failure_description
Equality Tests
STAssertEqualObjects
Fails the test case when two objects are different.
STAssertEqualObjects(object_1, object_2, failure_description, ...)
Parameters
Unconditional Failure
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
85
APPENDIX B
object_1
An object.
object_2
An object.
failure_description
STAssertEquals
Fails the test case when two values are different.
STAssertEquals(value_1, value_2, failure_description, ...)
Parameters
value_1
STAssertEqualsWithAccuracy
Fails the test case when the difference between two values is greater than a given value.
86
Equality Tests
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
APPENDIX B
Parameters
value_1
Nil Tests
STAssertNil
Fails the test case when a given expression is not nil.
STAssertNil(expression, failure_description, ...)
Parameters
expression
Expression to test.
failure_description
Nil Tests
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
87
APPENDIX B
STAssertNotNil
Fails the test case when a given expression is nil.
STAssertNotNil(expression, failure_description, ...)
Parameters
expression
Expression to test.
failure_description
Boolean Tests
STAssertTrue
Fails the test case when a given expression is false.
STAssertTrue(expression, failure_description, ...)
Parameters
expression
Expression to test.
failure_description
STAssertFalse
Fails the test case when a given expression is true.
STAssertFalse(expression, failure_description, ...)
Parameters
88
Boolean Tests
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
APPENDIX B
expression
Expression to test.
failure_description
Exception Tests
STAssertThrows
Fails the test case when an expression doesnt raise an exception.
STAssertThrows(expression, failure_description, ...)
Parameters
expression
Expression to test.
failure_description
STAssertThrowsSpecific
Fails the test case when an expression doesnt raise an exception of a particular class.
STAssertThrowsSpecific(expression, exception_class, failure_description, ...)
Parameters
expression
Expression to test.
exception_class
An exception class.
Exception Tests
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
89
APPENDIX B
failure_description
STAssertThrowsSpecificNamed
Fails the test case when an expression doesnt raise an exception of a particular class with a given name.
STAssertThrowsSpecificNamed(expression, exception_class, exception_name,
failure_description, ...)
Parameters
expression
Expression to test.
exception_class
An exception class.
exception_name
STAssertNoThrow
Fails the test case when an expression raises an exception.
STAssertNoThrow(expression, failure_description, ...)
90
Exception Tests
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
APPENDIX B
Parameters
expression
Expression to test.
failure_description
STAssertNoThrowSpecific
Fails the test case when an expression raises an exception of a particular class.
STAssertNoThrowSpecific(expression, exception_class, failure_description, ...)
Parameters
expression
Expression to test.
exception_class
An exception class.
failure_description
STAssertNoThrowSpecificNamed
Fails the test case when an expression doesnt raise an exception of a particular class with a given name.
STAssertNoThrowSpecificNamed(expression, exception_class, exception_name,
failure_description, ...)
Parameters
expression
Exception Tests
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
91
APPENDIX B
Expression to test.
exception_class
An exception class.
exception_name
STAssertTrueNoThrow
Fails the test case when an expression is false or raises an exception.
STAssertTrueNoThrow(expression, failure_description, ...)
Parameters
expression
Expression to test.
failure_description
STAssertFalseNoThrow
Fails the test case when an expression is true or raises an exception.
STAssertFalseNoThrow(expression, failure_description, ...)
Parameters
expression
92
Exception Tests
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
APPENDIX B
Expression to test.
failure_description
Exception Tests
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
93
APPENDIX B
94
Exception Tests
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
Glossary
95
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
GLOSSARY
96
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
REVISION HISTORY
Notes
2010-07-02
Changed the title from iPhone Development Guide. Updated Hello, World!
tutorial to iPhone SDK 4.0.
Updated Hello, World! tutorial and source code ("Tutorial: Hello, World!" (page
17) and "Hello, World! Source Code" (page 83)) for iPhone SDK 4.0 toolset.
2010-05-28
2010-03-19
2010-01-20
2009-08-06
Added information about editing property-list files, linking static libraries, and
iPhone Simulator versions. Made minor changes.
Added "Editing Property-List Files" (page 25).
97
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
REVISION HISTORY
Date
Notes
Added important information about debugging applications on devices to
"Debugging Facilities Overview" (page 55).
Added "Setting the Simulation-Environment Device Family and iOS
Version" (page 43).
2009-05-28
2009-05-14
2009-04-08
2009-03-04
2009-02-04
2009-01-06
2008-11-14
2008-10-15
New document that describes how to develop iPhone applications using Xcode.
98
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
REVISION HISTORY
Date
Notes
Incorporates content previously published in iPhone OS Programming Guide and
iPhone Simulator Programming Guide.
99
2010-07-02 | 2010 Apple Inc. All Rights Reserved.
REVISION HISTORY
100
2010-07-02 | 2010 Apple Inc. All Rights Reserved.