Anda di halaman 1dari 292

Xcode 4 User Cuide

Contents
Abeut Xcede 12
At a Clance 12
Cet Oriented to Xcode Organization and Peatures 13
Design the Look and 8ehavior of our App 13
Debug and Pefine our Code 13
Safeguard our Pro|ects Using Source Control 13
Distribute our App to App Testers or Publish it on the App Store 14
See Also 14
Cet Driented 15
Contextual Help: our Shortcut to Answers 15
The workspace window: where ou Cet Most of our work Done 16
Open work in Tabs and windows 18
Ldit and view Many Types of Data 19
Pind |nformation to view or Ldit 31
Pind |nformation that Supplements the Lditor 47
Check on the Progress of Xcode Tasks 50
The Organizer window: Managing Pro|ects, Devices, and Documentation 51
8rowse and 8ookmark Documents 51
8rowse for Task-8ased Help 54
work with our Source Control Pepositories 54
Organize our Pro|ects and Devices 55
Take a Snapshot of our Pro|ect 55
Start a Preject 56
Click New Pro|ect in the Xcode 4 Startup Screen to Create a Standalone Pro|ect 56
Create a Cit Pepository Por our New Pro|ect 58
Select Options while Creating a New Pro|ect 58
Create a workspace to work with Multiple Pelated Pro|ects 59
Check Out a working Copy from our Source Control Pepository 63
Modernize our Pro|ect 63
Add Automatic Peference Counting 64
Close a Pro|ect or a workspace 65
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
2
Cenfigure eur Preject 66
Add 8uild Configurations 66
Set the 8asic 8uild Settings 69
Add 8uild Pules 72
dit User Interfaces 76
Create our User |nterface 76
Display our User |nterface Ob|ects 78
Connect to Other Piles Using Placeholder Ob|ects 79
Select Hidden Ob|ects in an |nterface Pile 82
Lay Out User |nterface Controls Using Content-Driven Pules 84
Add New Constraints 87
Allow Ob|ects to Maintain Their |ntrinsic Content Size 90
Override Automatic Constraints 91
Set Priorities to Pesolve Potential Conflicts 92
Design the User |nterface of our iOS App with Storyboards 92
Create User |nterface Classes 97
Add a New Nib Pile 98
Add a Custom view 102
Add a New Controller 103
Simultaneously Design and |mplement User |nterface Ob|ects Using Multiple Lditors 117
Manage Connections 8etween User |nterface Ob|ects 106
Make Connections Directly 8etween |8 Ob|ects and our Code Piles 107
Add Outlets and Actions to Classes Programmatically 110
Use the |nspector or the Connections Panel to Make Connections 111
Configure Connections 8etween Model and view Ob|ects 114
Create and Configure a 8inding with the 8indings |nspector 115
Create a 8inding by Dragging Directly to our Header Pile 116
Key Paths Are Dependent on our Data Model 117
Configure the 8inding Attributes to Customize the 8inding 118
8ind to Ob|ects in a Custom Tree Data Structure 118
8ind to our Application Preferences 119
dit Seurce Cede 121
Customize the Source Lditor with Xcode Preferences 121
Modify Syntax-Aware Ponts and Text Colors 121
Set our Text-Lditing and Automatic |ndentation Preferences 125
Lnter Code uickly and Accurately with the Help of the Source Lditor 125
Speed Up Typing with Code Completion 125
8alances Delimiters Automatically 128
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
3
Centents
Have Pix-it Plag Lrrors as ou Type 129
Pind and Display Pelated Content 130
Open a P|le uickly 130
Split the Lditor Area to Display Pelated Content 132
Customize Keyboard Shortcuts to Determine where a Pile's Contents Are Displayed 134
1ump to a Symbol's Definition 136
Pind Pelated |tems with the 1ump 8ar 138
Pind Pelated Content Automatically 138
Use Assistant with |nterface 8uilder and Data Models 140
|ncorporate Other Source Lditor Peatures into our workflow 141
Lxamine the Structure of our Code with Code Polding 141
view Preprocessor or Assembly Output 143
view Documentation for a Symbol Using uick Help 144
Automate Lxtensive Changes in our Piles 147
|ncorporate Piles and Code from the Xcode Libraries 148
Use |nspectors to view and Lnter Data 152
8uiId and Run eur App 153
Create, Ldit, and Manage Schemes 178
Specify which Targets Are 8uilt for Lach Type of Action 155
Pename or Peorganize our Schemes 156
Configure and Lxecute Actions 158
Pun our Application to Debug |t 158
Pun Unit Tests to Pind Pegressions 163
Profile our Application to Pind Problems and Optimize our Code 168
Perform Static Analysis To Pind Semantic Problems 169
Create an Archive for Sharing or Submitting our Program 169
|nitiate an Action 170
Customize our 8uild and Pun workflow 172
Pine-Tune our 8uilds 176
Control the Order in which Xcode 8uilds our Products 178
Debug eur App 180
Select a Debugger 180
Pind Coding Mistakes 181
Locate Possible Semantic Problems 181
Locate and Display 8uild |ssues 183
Manage 8reakpoints 188
Add and Activate 8reakpoints 188
Ldit 8reakpoints 190
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
4
Centents
Share 8reakpoints 192
Set Preferences for 8reakpoint 8ehavior 193
Customize the Debug Area 194
The variables Pane 194
The Console Pane 195
Control Program Lxecution 195
Step Through Code with the Debug 8ar 195
Set a Location in the Debug 8ar 196
Step Through Code in the Source Lditor 196
Suspend a Thread 197
Set Xcode window 8ehavior 199
Lxamine Threads, Stacks, variables, and Memory 200
Capture OpenCL LS Prames 206
Make Prejectwide Cbanges 215
Peplace Text Strings 215
Peplace All |nstances of a Text String 216
Peplace Selected |nstances of a Text String 218
Customize the Search 219
|mprove our Code's Structure Through Pefactoring 221
Select the Source Code to Pefactor 221
Preview the Changes 8efore Lxecuting the Operation 222
Pun Unit Tests 8efore and After Pefactoring 222
Choose a Pefactoring Operation 223
Manage eur Devices 225
Set Up our Device 226
Provision a Device 226
Pestore or |nstall a version of iOS on a Device 229
Pun our Application On the Device 230
Pemove an Application from a Device 230
Download our Application's Data for Analysis 232
Capture and Use Screenshots from a Device 234
Set a Screenshot as our iOS Application's Launch |mage 235
Lxport a Screenshot to our Pile System 237
|dentify Small U| Changes by Comparing Screenshots 238
Transfer our Developer Profile to Another Computer 239
Save and Revert Cbanges te IiIes 244
Save when Lditing 244
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
5
Centents
Pevert to the Last Saved version 244
Undo Changes |ncrementally 246
Unlocking Piles 247
Use Snapshots and SCM for Pro|ectwide Change 249
Snapshots Archive Pro|ectwide Changes to Documents and Configuration 249
SCM Pepositories Manage Overall Change as our Pro|ect Develops 249
Save and Revert Cbanges te Prejects 251
Take a Snapshot of our Pro|ect 252
Keep Track of Changes with Source Control 253
why Use Source Control! 277
Choose Cit or Subversion 254
Learn SCM Terminology 254
Manage our Pepositories 256
Pind SCM Commands 258
Keep Track of our Piles' SCM Status 260
work with Cit and Subversion 261
Set Up Cit version Control when ou Create a New Pro|ect 261
Add Cit or Subversion version Control to an Lxisting Pro|ect 261
Clone or Check Out a Copy of a Pro|ect to Use Locally 264
Add an Lxisting SCM working Copy of a Pro|ect to Xcode 265
Create a 8ranch to |solate Pisky Changes 265
Clone a Specific 8ranch 268
Add a Polder to a Subversion Pepository 270
Commit Piles to Add Them to a Pepository 271
Peconcile Different 8ranches 272
Update our working Copy from a Pemote Pepository 273
Send our working Copy to the Pemote Cit Pepository 277
Save |nternal Pro|ect Piles in Pepositories 278
Compare Pevisions 278
Select Specific Pevisions 279
Peview |ndividual Changes 280
view All Pevisions Chronologically 281
Distribute our Program 282
Distribute eur App 284
Archive our App 287
validate our App 285
Distribute our iOS App 287
Distribute our Mac App 289
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
6
Centents
Decument Revisien Histery 291
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
7
Centents
Pigures and Tables
Cet Driented 15
Pigure 1-1 Contextual help 15
Pigure 1-2 A newly opened Xcode window 16
Pigure 1-3 The pro|ect contents in the Xcode pro|ect navigator 16
Pigure 1-4 The utility area 17
Pigure 1-5 The debug area 18
Pigure 1-6 The source editor 21
Pigure 1-7 Target information in the pro|ect editor 38
Pigure 1-8 8uild settings 23
Pigure 1-9 uick Help for key values 24
Pigure 1-10 The data model editor 28
Pigure 1-11 The mapping model editor 29
Pigure 1-12 |nterface 8uilder 30
Pigure 1-13 Lditor selector buttons 31
Pigure 1-14 The navigators 31
Pigure 1-15 A folder and groups in the pro|ect navigator 33
Pigure 1-16 The pro|ect navigator filtered to show only .m files 36
Pigure 1-17 Pro|ect navigation 36
Pigure 1-18 The |ump bar in |nterface 8uilder 38
Pigure 1-19 The related items pop-up menu 39
Pigure 1-20 The Pind Options dialog 42
Pigure 1-21 The issue navigator 43
Pigure 1-22 The breakpoint navigator 44
Pigure 1-23 The debug navigator and associated editor and debug areas 45
Pigure 1-24 viewing a log 46
Pigure 1-25 The utility button 47
Pigure 1-26 Data model inspectors 48
Pigure 1-27 |nterface 8uilder inspectors 48
Pigure 1-28 The library pane 49
Pigure 1-29 The activity viewer 50
Pigure 1-30 The activity pop-up window 50
Pigure 1-31 |ssues in the activity viewer 50
Pigure 1-32 The Organizer button 51
Pigure 1-33 The documentation navigator 51
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
8
Pigure 1-34 The bookmarks navigator 52
Pigure 1-35 Xcode help start screen 54
Start a Preject 56
Pigure 2-1 The option to add source control when creating a pro|ect 58
Pigure 2-2 Options for a new pro|ect 59
Pigure 2-3 A shortcut menu for a workspace 62
Pigure 2-4 Modernization in the |ssue navigator 63
Pigure 2-5 Updates dialog 64
Cenfigure eur Preject 66
Table 3-1 Mac OS X pro|ect editor Summary pane settings 70
Table 3-2 iOS pro|ect editor Summary pane settings 72
dit User Interfaces 76
Pigure 4-1 |nterface 8uilder in the workspace window 77
Pigure 4-2 |con view for placeholders and ob|ects in |nterface 8uilder 78
Pigure 4-3 Auto Layout 85
Pigure 4-4 User constraint 88
Pigure 4-5 8utton set to maintain its intrinsic content size 90
Pigure 4-6 Automatic constraints 91
Pigure 4-7 User-added trailing constraint 91
Pigure 4-8 User-added leading constraint 92
Pigure 4-9 The Use Storyboard option 93
Pigure 4-10 view controllers in the ob|ect library 94
Pigure 4-11 Creating a storyboard 95
Pigure 4-12 Attributes inspector for a segue 96
Pigure 4-13 Storyboard for an iOS Application 97
Pigure 4-14 |nterface 8uilder and Assistant 106
Pigure 4-15 Making a connection to source code from |nterface 8uilder 107
Pigure 4-16 Help articles in |nterface 8uilder 110
Table 4-1 Auto Layout constraints 88
dit Seurce Cede 121
Pigure 5-1 Ponts & Colors preferences 122
Pigure 5-2 Code completion 126
Pigure 5-3 uick Help for code completion 128
Pigure 5-4 Placeholders in code completion text 128
Pigure 5-5 The Assistant button 132
Pigure 5-6 Ceneral preferences 134
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
9
Iigures and 7abIes
Pigure 5-7 The Single Assistant navigation chooser dialog 135
Pigure 5-8 The navigation chooser dialog 136
Pigure 5-9 The assistant editor used with a data model 140
Pigure 5-10 The focus ribbon in use 142
Pigure 5-11 Preprocessor output 143
Pigure 5-12 Cenerated output in Assistant |ump bar 144
Pigure 5-13 The uick Help window 145
Pigure 5-14 A file template information pop-up window 149
Pigure 5-15 The Pile inspector 152
8uiId and Run eur App 153
Pigure 6-1 The Scheme pop-up menu 153
Pigure 6-2 The manage schemes dialog 157
Pigure 6-3 The scheme editor Pun pane 158
Pigure 6-4 Choosing a location in the scheme editor 163
Pigure 6-5 8ehaviors preferences 172
Pigure 6-6 Pro|ect editor help topics 176
Debug eur App 180
Pigure 7-1 The issue navigator 183
Pigure 7-2 The debug area 194
Pigure 7-3 Choosing a location in the debug bar 196
Pigure 7-4 Xcode |n Pront window mode while the executable is running 199
Pigure 7-5 Xcode |n Pront window mode while the executable is paused 200
Pigure 7-6 Lnabling OpenCL LS frame debugging 207
Pigure 7-7 Prame capture button 208
Pigure 7-8 OpenCL LS frame capture 209
Pigure 7-9 Controls for stepping through draw calls 210
Pigure 7-10 Shortcut menu 211
Pigure 7-11 wireframe view 212
Pigure 7-12 Prame capture with two Assistant panes 213
Pigure 7-13 vertex Array Ob|ect detail 214
Make Prejectwide Cbanges 215
Pigure 8-1 Search and replace using the search navigator 215
Pigure 8-2 The refactor preview dialog 222
Manage eur Devices 225
Pigure 9-1 Devices organizer 225
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
10
Iigures and 7abIes
Save and Revert Cbanges te IiIes 244
Pigure 10-1 workspace window with in-memory changes to files 245
Pigure 10-2 Undo Typing command 246
Pigure 10-3 Pile could not be unlocked 247
Pigure 10-4 Locked file indicators 248
Save and Revert Cbanges te Prejects 251
Pigure 11-1 The Snapshots settings dialog 252
Pigure 11-2 Snapshots listed in the Organizer window 253
Pigure 11-3 The repositories pane in the Organizer window 256
Pigure 11-4 The Source Control submenu of the Pile menu 259
Pigure 11-5 The Source Control submenu of the pro|ect navigator shortcut menu 259
Pigure 11-6 Pepositories organizer buttons 259
Pigure 11-7 Source control badges in the pro|ect navigator 260
Pigure 11-8 A scheme in the commit dialog 278
Pigure 11-9 Comparing two revisions of a file with the version editor 279
Pigure 11-10 The archives organizer 283
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
11
Iigures and 7abIes
Xcode is the integrated development environment (|DL) designed for developing iOS and Mac apps. The Xcode
|DL includes editors used to design and implement your app, such as a source code editor and a user interface
editor. Xcode also supports multiperson development using source control management (SCM) systems. As
you write source code, Xcode can show you mistakes in both syntax and logic, and even suggests fixes.
Xcode features a single window, called the wotlsoce w|nJow, that holds most of the data you need.
Toolbar
Debug
area
Library pane
Inspector pane
Debug bar
Utility
area
Navigator
selector bar Jump bars
Inspector
selector bar
Library
selector bar
Navigator
area
Breakpoint gutter
Focus ribbon
Filter bar
Editor
area
Pead this guide to get started using Xcode.
At a Clance
Xcode has many features to make your |ob easier.
!
SingIe-windew interface. ou perform most of your development workflows in one window (you can
have multiple workspace windows and multiple tabs per window).
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
12
About Xcode
!
CrapbicaI user interface design. with the Xcode user interface editor, called |nterface 8uilder, you specify
most of the details of your app's user interface, such as the layout of the user interface controls, and their
connection to your app's business logic and the data it manages, using a powerful and intuitive graphical
user interface. |nterface 8uilder works closely with other editors, such as the source code editor, to take
you from design to implementation as fast as possible.
!
Assisted editing. when you need to work on different aspects of the same component, such as user
interface layout and the implementation of the user interface functionality, you can use multiple editors
that open the content you need when you need it. Por example, when you work on an implementation
file in the primary editor, Xcode can open the corresponding header file in a secondary editor pane.
!
Autematic errer identificatien and cerrectien. Xcode checks the source code you type as you type it.
when Xcode notices a mistake, the source code editor highlights it. ou can then find out details about
the error and ask Xcode to fix it for you.
!
Seurce centreI. ou can safeguard all your pro|ect files in Cit and Subversion source code repositories.
Cet Oriented to Xcode Organization and Peatures
Xcode is a powerful tool. 8ut, as it's true with any complex product, you need to know essential concepts and
workflows before you can start developing products efficiently.
Pelevant Chapters: "Cet Oriented" (page 15), "Start a Pro|ect" (page 56).
Design the Look and 8ehavior of our App
Two of the most important tasks you perform while you develop your app is designing its user interface and
writing the business code that implements your app's unique functionality.
Pelevant Chapters: "Ldit User |nterfaces" (page 76), "Ldit Source Code" (page 121).
Debug and Pefine our Code
Xcode provides a debugging environment that you can customize to automatically bring forward the parts of
your code in which you are interested the most.
Pelevant Chapters: "Debug our App" (page 180), "Make Pro|ectwide Changes" (page 215).
Safeguard our Pro|ects Using Source Control
Xcode provides easy local backups with snapshots and the ability to work in a team using SCM.
Pelevant Chapter: "Save and Pevert Changes to Pro|ects" (page 251).
Abeut Xcede
At a Clance
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
13
Distribute our App to App Testers or Publish it on the App Store
Share your app with other members of your development team or app testers, or publish it on the App Store.
Pelevant Chapters: "Distribute our App" (page 284).
See Also
8efore developing your iOS or Mac app, you must be familiar with the design and coding practices required
by your target platform. See 0evelo|n lot tle A 5tote to learn the basics of app development.
Abeut Xcede
See Also
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
14
Once you've got your pro|ects open in Xcode, you can start writing code. This chapter describes where to find
the most commonly used features of Xcode. The remaining chapters describe the use of some of these features
in more detail.
Contextual Help: our Shortcut to Answers
|n addition to being listed in the documentation browser in Xcode ("8rowse for Task-8ased Help" (page 54)),
many help articles are available from shortcut menus throughout the application. Control-click in any of the
main user-interface areas in the workspace or Organizer window to see a list of help articles available for that
area. Pigure 1-1 shows contextual help for the source editor. |f there are more articles than can be listed in the
shortcut menu, choose Show All Help Topics, the help opens in the Organizer window (Pigure 1-35 (page 54)).
ou can use this facility to find information about a specific task that you're trying to accomplish, or |ust to
learn what tasks can be performed using that area of Xcode.
Iigure 1-1 Contextual help
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
15
Cet Oriented
The workspace window: where ou Cet Most of our work Done
8efore going any further, you need to get oriented to the Xcode workspace window (Pigure 1-2).
Iigure 1-2 A newly opened Xcode window
The left side of the window is the navigator area, opened to the pro|ect navigator in the figure. The pro|ect
navigator shows the contents of your pro|ect or workspace. Pigure 1-3 shows some of the groups and files in
a pro|ect.
Iigure 1-3 The pro|ect contents in the Xcode pro|ect navigator
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
16
The right side of the window in Pigure 1-2 (page 16) is the editor area. ou can edit many types of information,
including source code, property lists (plists), Core Data models, and user interface (nib or storyboard) files, and
you can view many more.
To supplement the information in the editor area, you can open a utility area at the right of the workspace
window (Pigure 1-4), which includes inspectors and libraries. Use the view selector ( ) in the toolbar
to open and close the navigator, debug, and utility areas.
Iigure 1-4 The utility area
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
17
when you are running code, the debug area opens (Pigure 1-5). when you stop at a breakpoint, the debug
navigator opens as well.
Iigure 1-5 The debug area
Open work in Tabs and windows
Por fast switches between different editors or files, you can add tabs to the Xcode workspace window, or you
can open additional windows. To activate tabs, choose view > Show Tab 8ar, or add a new tab by choosing
Pile > New > New Tab. Choose Pile > New > New window to open a new workspace window. Lach tab or
workspace window can be customized independently of the others. Por example, you can use one window to
debug and another to edit source code. |f you open the same file in two tabs or two windows, the changes
you make in one tab or window are reflected in the other.
Tabs can be reordered, closed independently, or dragged out of the tab bar to create a new window, |ust as
they can in Safari. ou can use items in the window menu (or their keyboard equivalents) to move between
tabs. ou can also give a tab a name for use in 8ehaviors preferences (see "Customize our 8uild and Pun
workflow" (page !)).
Xcode remembers the windows and tabs you had open when you last closed a workspace and reopens them
in the same configuration.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
18
Ldit and view Many Types of Data
Xcode includes editors for many file types, including:
!
Source code
!
Pro|ect and build settings
!
Property list (plist) files
!
Pich text (rtf ) files
!
Core Data models
!
Core Data mapping models
!
User interface (nib) files
!
AppleScript files
!
Scripting dictionary files
There are viewers that can display graphics, videos, and a variety of other file types.
The use of each of these editors is briefly described in this section. Control-click in any of the editors to get a
list of help articles that further describe the use of the editor (Pigure 1-1 (page 15)).
Select Any Pile
To open any of the editors or viewers, select a file in the pro|ect navigator. The editor or viewer for that file
type opens automatically in the editor area of the workspace window. Any file for which Xcode does not have
an editor is displayed using uick Look. (uick Look is also used by the Pinder. |n the Pinder, select a file and
press the Space bar or choose uick Look from the Pile menu to see it in use.)
Lach document-type editor has customcommands in the Navigate and Lditor menus to act on the information
in that type of document. Note that the Navigate menulike several of the menus in Xcodeshows different
menu items when you hold down the Option, Shift, or Option and Shift keys.
Ldit in Hexadecimal Pormat
ou can view most file types in hexadecimal format by Control-clicking the file in the pro|ect navigator and
choosing Open As > Hex from the shortcut menu. Some file types that are not editable in the default viewer,
such as image files, can be edited in hexadecimal format.
ou can edit the hexadecimal code directly, or you can edit in the plain text column. Lditing either updates
the other.
when the hex editor has focus, you can use the Lditor menu to customize its display.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
19
view and edit a file in its binary format by opening it in the hex editor.
7e epen a fiIe witb tbe bex editer . . .
1. Control-click a file in the pro|ect navigator.
2. Choose Open As > Hex.
The hex editor has three areas:
!
On the left, the line numbers
!
|n the center, the hexadecimal representation of the bytes in the file, 32 bytes per line, one byte per
column
!
On the right, the plain-text (ASC||) representation of those bytes
Prom the Lditor menu, you can hide the line numbers or the plain-text representation. ou can also choose
to display the byte codes in groups of 2, 4, 8, 16, or 32.
The screenshot shows an image file in the hex editor.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
20
write, Ldit, and Debug Source Code
The Xcode source editor has many features to help you develop source code. Among other features, you can
write and edit source code (see "Ldit Source Code" (page 121)), set and enable or disable breakpoints (see
"Manage 8reakpoints" (page 188)), and control program execution during a debugging session (see "Control
ProgramLxecution" (page 195)). Control-click in the source editor to see a list of help topics describing features
of the editor and tasks you can accomplish (Pigure 1-1 (page 15)).
Iigure 1-6 The source editor
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
21
Nete: when you edit a file in Xcode, the file's icon is shaded in the pro|ect navigator to indicate
that there are unsaved changes. ou can save the file, or if you quit Xcode or build the pro|ect, Xcode
automatically saves all changed files for you by default (you can change this behavior in the Ceneral
pane of Xcode preferences). To ensure you can return to a known state before you build your pro|ect,
create a snapshot (see "Take a Snapshot of our Pro|ect" (page 55)).
Ldit 8uild Settings
when you click the pro|ect icon in the pro|ect navigator, the pro|ect editor appears to the right of the pro|ect
navigator, displaying pro|ect and target information. Pigure 1-7 shows some of the target information in the
pro|ect editor.
Iigure 1-7 Target information in the pro|ect editor
Click the various buttons and icons in the pro|ect editor to see the information that's in there.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
22
ou can choose to viewbasic build settings or all settings. The values of build settings can be set at the default,
pro|ect, or target level. ou can edit a build setting at the pro|ect or target levels. Click the Levels button to
see all the levels of build settings simultaneously, as in Pigure 1-8. The setting that takes precedence is
highlighted in green and shown in the Pesolved column. |f you have changed or customized a setting, it's
shown in boldface. Click the Combined button to see |ust the resolved build settings.
Iigure 1-8 8uild settings
See "To add a new build configuration" (page 66) for more information on using build settings.
Ldit Keys and values
|n addition to the Th1o.p11s1 file required for every application, the property list editor opens a variety of
other property list file types.
To edit a key or a value, double-click the item and type a new string into the text field. |n some cases, a pop-up
menu is available, indicated by small vertical arrows. Click the arrows to see the choices.
ou can add a new property or you can add a new child property for an array or dictionary. The property list
editor warns you if you attempt to add a key that already exists in the file.
Add a new property to a property list using the property list editor.
7e add a preperty te a preperty Iist . . .
1. |n the property list editor, hold the pointer over an entry and click the Add (+) button.
2. Choose a key name from the pop-up menu.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
23
3. Choose a value from the pop-up menu in the value column or enter a value.
|f you are adding a property that is an array or dictionary, click the disclosure triangle and press Peturn to
add a child property.
ou can add a property with a name that is not in the pop-up menu. To do so, type the key name in the
field at the top of the pop-up menu, choose the data type from the pop-up menu in the Type column, and
enter a value in the value column.
Click the minus (-) sign next to any item to remove it from the file.
Por known property list key types, the Key column in the property list editor shows a descriptive name of the
key instead of the key's literal text. Choose Lditor > Show Paw Keys & values to display the literal text instead.
ou can also see both the name and the raw key value in uick Help in the utility area (Pigure 1-9).
Iigure 1-9 uick Help for key values
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
24
Control-click in the editor and select Property List Type to see a list of possible file types for property lists. The
type of the current file is indicated by a dash to the left of the file name. ou can use this menu to change from
the default to a specific property type.
Set the property list type when creating or editing a property list. |f Xcode cannot determine the type of a
property list, you may need to set the type manually.
7e set tbe preperty Iist type . . .
1. Select a property list in the pro|ect navigator.
2. Control-click in the property list editor to display a contextual menu.
3. Prom the Property List Type submenu, choose a new property list type.
Property lists that share the same system-defined structure are said to have the same type. |n addition to
the Th1o.p11s1 file required for every application bundle, the property list editor in Xcode supports a
variety of other types. The property list type determines the list of possible keys in the key's pop-up menu.
|n the Property List Type submenu, the current type is indicated by a dash to the left of the type name.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
25
Ldit Pich Text Piles
ou can write, open, and edit rich text (.J11) files in Xcode. The editor has a user interface and feature set
very similar to those of the Mac OS X TextLdit application, but without the capability of converting the file to
other formats such as plain text or HTML. Note that Xcode opens plain text (.1x1) files with the source editor,
not the rich text editor.
Design Data Models Craphically
|f your pro|ect uses the Core Data framework, you can use the data model editor to implement or modify your
Core Data model (see Cote 0oto 5tott|n lo|nt ).
Cet a |ump-start on your Core Data-based pro|ect by using one of the pro|ect templates that incorporate Core
Data.
7e create a preject tbat uses Cere Data . . .
1. Choose Pile > New > Pro|ect.
2. Select the pro|ect template for your iOS or OS X product, and click Next.
3. |f the Use Core Data option appears in the pro|ect options pane, select it and click Next.
Otherwise, Core Data is not available in the selected pro|ect template.
4. Lnter the pro|ect name, and specify its location in your file system.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
26
5. Click Create.
The pro|ect templates that incorporate Core Data:
!
Link against the Core Data framework
!
Add a managed ob|ect model file
!
Add code to create and locate the various parts of the Core Data stack
Use the Core Data model editor to edit the managed ob|ect model.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
27
Impertant: Not all templates offer a Core Data option.
Core Data is an advanced technology that is not required for creating simple applications.
The managed ob|ect model is a representation of the schema that describes your model ob|ects, including
the relationships between them. Pigure 1-10 shows the data model editor.
Iigure 1-10 The data model editor
The top-level components area lists the entities, fetch requests, and configurations defined in the model. ou
can select one or more items at a time within a single group. ou use the Add Lntity button to add an entity,
fetch request, or configuration. To add a fetch request or configuration, press and hold the Add Lntity button
until it shows the other options. The button retains the label from the last time it was used.
The detail area shows the attributes, relationships, and fetched properties associated with the item or items
you select in the top-level components area. ou can select one or more items from the same group at the
same time. There are two styles for the detail area: table and graph. ou select the style using the segmented
control at the lower right of the editor area. ou can use the graph style only if you select an entity in the
top-level components area. ou can use either style to edit the model, however the table style is typically
better for detailed editing and inspection, and the graph style is better for visualizing your schema.
The Core Data Model inspector in the utility area displays information about the item or items you select in
the detail area. 8y selecting more than one property in the detail area, you can edit several properties at the
same time. Por example, you can set the Attribute Type for a number of attributes simultaneously.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
28
Define Pules Used in Data Store Migration
|f you change your Core Data model extensively enough that you need a mapping between an old store and
a new one, you can use the Core Data mapping model editor to graphically create the mapping model.
A Core Data mapping model describes the transformations needed to convert data described by a Core Data
model to another Core Data model with a different schema. The Core Data mapping model editor provides
table-based tools to create and edit a mapping model.
7ip: 8efore you create a mapping model, you should consider whether you can transform your data using
lightweight migration(as describedinCote0otoVoJel vets|on|nonJ0otoV|tot|onltotomm|nCu|Je ).
Lightweight migration is much simpler and more efficient than mapping model-driven migration. |n some cases,
you can make custom transformations by first using lightweight migration, and then performing an additional
step in code.
The mapping model editor is shown in Pigure 1-11.
Iigure 1-11 The mapping model editor
The entity mappings list lists all the entity mappings defined in the model. ou can edit the name of the
mapping by double-clicking the text.
The property mapping tables show the attribute and relationship mappings associated with the currently
selected entity mapping.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
29
The new entity mapping management area allows you to add a new entity mapping to the model.
Click the Add Lntity Mapping button to display a series of dialogs that you use to configure the new mapping.
|f necessary, you choose the source and destination models for the entity using the corresponding pop-up
menus.
Por complete flexibility, you can implement a subclass of NSEh111y^1gJa11ohPo11cy to set it as the custom
policy for a mapping.
Design our User |nterface Craphically
Starting with the first version of Xcode, Apple provided a separate applicationcalled |nterface 8uilderfor
designing graphical user interfaces. |n Xcode 4, |nterface 8uilder is fully integrated into the workspace window
as an editor. Pigure 1-12 shows |nterface 8uilder in Xcode 4.
Iigure 1-12 |nterface 8uilder
|nterface 8uilder creates filescalled nib filesthat are in a proprietary format (that is, you can't read them
with the source editor or the hex editor). Por more information on the use of |nterface 8uilder, see "Ldit User
|nterfaces" (page 76).
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
30
Display Piles in a Split Lditor Pane
ou can display two or more different views of a file, two or more different files, or two different versions of
the same file in ad|acent editor panes (side by side or one above the other). ou use the editor selector buttons
(Pigure 1-13) to switch between the standard editor, Assistant, and the version editor. whereas the standard
editor uses a single editor pane, Assistant and the version editor use a split-pane editor. |n addition, if you
Option-click a file in the pro|ect navigator or symbol navigator pane, that file opens in the assistant editor pane
(you can change this behavior in the Ceneral pane of Xcode preferences).
Iigure 1-13 Lditor selector buttons
Although you can specify which file to show in each pane of the split editor, it is often helpful to let Xcode find
a related file for you. Assistant can find, for example, the header file counterpart to the source code file you're
viewing, or the source code file used to implement the control code for an |nterface 8uilder file. Por more
information about Assistant, see "Split the Lditor Area to Display Pelated Content" (page 132).
|f your pro|ect is under source control, the version editor can compare any two versions of the file, see "Compare
Pevisions" (page 278) for details.
Pind |nformation to view or Ldit
Xcode provides two ways to navigate through your pro|ect: navigators and the |ump bar. Many of the navigators
include text fields for searching through the pro|ect or filtering the items in the navigator, some include buttons
to restrict the scope of items displayed. The |ump bar appears at the top of the editor pane and provides an
alternate way to navigate through the files and symbols in the pro|ect. 8ecause the |ump bar is always available,
you can use it to find items in the pro|ect even when the navigator area is closed.
The navigators are shown in Pigure 1-14.
Iigure 1-14 The navigators
Breakpoint Issue Symbol
Log Search Debug Project
The use of each of these navigators and |ump bars is briefly described in this section. Control-click in any of
the navigators to get a list of help articles that further describe the use of the navigator.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
31
view the Piles in our Pro|ect or workspace
The pro|ect navigator shows pro|ects, groups, folders, and files:
!
The preject or pro|ects in your workspace window are the highest level of the hierarchy in the pro|ect
navigator. Open the pro|ect's disclosure triangle to see the groups, folders, and files in the pro|ect. Select
the pro|ect to display the pro|ect editor, where you can view and edit pro|ect and target settings.
!
A greup appears in the pro|ect navigator as a yellow folder icon. The group does not represent a folder
on disk. Although you can organize your pro|ect in Xcode to reflect the organization of files on disk, moving
files into and out of groups does not affect the content of the folders on disk, and moving files on disk
into and out of folders does not affect the content of the groups in the pro|ect navigator.
!
A feIder is a reference to a folder on disk and appears in the pro|ect navigator as a blue folder icon. The
contents of the folder in the pro|ect navigator reflect the contents of the folder on disk. |t's important to
note, however, that the files that appear in a folder icon in the pro|ect navigator are not part of your pro|ect
unless you have added themto the pro|ect explicitly (in which case they appear directly under the pro|ect
or in a group, as well as in the folder). ou can view and edit the files in a folder, but to move files in and
out of the folder you must use the Pinder.
!
A fiIe in the pro|ect navigator is a reference to a file on disk.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
32
Pigure 1-15 shows a pro|ect (Fo1deJF1hdeJ) containing both a group and a folder named Ex1JaF11es.
Although in the figure the group contains the same files as the folder, you could modify the contents of either
the group or the folder without affecting the contents of the other container.
Iigure 1-15 A folder and groups in the pro|ect navigator
7e add existing fiIes te a preject
1. |n the pro|ect navigator, select the pro|ect or group to which you want to add the files.
Note that you can't add files to a folder in the pro|ect navigator. when you add a folder reference to
the pro|ect navigator, any changes you make to the contents of the folder in the Pinder are shown
immediately in the pro|ect navigator.
2. Choose Pile > Add Piles to "ltojectNome .
3. |n the dialog, select the file or files you want to add and click Add.
|f the file is not in your pro|ect folder on disk, you can choose to copy the file into your pro|ect folder.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
33
|f you select a folder in the dialog and select the "Create folder references for any added folders radio
button, Xcode adds a folder reference to the pro|ect navigator. Although the pro|ect navigator shows
the files that are in that folder on disk, Xcode does not add those files to your pro|ect. To add all the
files in a folder to your pro|ect, either select the files individually, or select the "Create groups for any
added folders radio button.
Click the New Polder button to add a folder to the disk and a reference to that folder to the pro|ect
navigator. Doing so does not add any files to your pro|ect.
ou can use the pro|ect navigator to organize the files in your pro|ect into groups and to list the files and
groups in any order you like. The |ump bar shows the same pro|ect organization as the pro|ect navigator down
to the file that's open in the editor, and then shows the individual symbols in the file.
Click the name of a file in the pro|ect navigator to see the file in the editor pane. The type of editor or viewer
that displays the file depends on the type of file you selected.
7e create a new greup
Do one of the following:
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
34
!
Place the cursor at the location in the pro|ect navigator where you want the group, Control-click, and
choose New Croup from the shortcut menu. ou can drag files into the group, and you can drag the
group to a new location in the navigator.
!
Select the files that you want to place in a new group, Control-click, and choose New Croup from
Selection. Note that you can Command-click items in the navigator to get a discontinuous selection.
Click the name of the group to edit the name.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
35
The pro|ect navigator has filters for recently edited files, files with source control status, unsaved files, and
filename strings. Pigure 1-16, for example, shows a pro|ect filtered to show only implementation (.m) files. The
filter field and buttons are at the bottom of the navigator area.
Iigure 1-16 The pro|ect navigator filtered to show only .m files
Once you've navigated to a file in the pro|ect navigator, you can see the path to that file displayed in the |ump
bar (Pigure 1-17). ou can use the |ump bar to navigate through your pro|ect.
Iigure 1-17 Pro|ect navigation
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
36
Use a |ump bar to directly navigate to items at any level in your workspace.
7e use tbe jump bar . . .
1. Click a level in the |ump bar and choose a file to |ump to.
2. To open a related file in Assistant, hold down Option and choose that file.
3. |n the Assistant |ump bar, choose a category of related files.
4. Use the stepper arrows to advance to the desired file.
5. Click the lock button to open a locked file, if appropriate.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
A |ump bar is an interactive, hierarchical mechanism for browsing items in your workspace. Lach editor
area includes a |ump bar, as do |nterface 8uilder and the documentation organizer. The configuration and
behavior of each |ump bar is customized for the context in which it appears. The basic configuration includes
three components:
!
The related items menu ( ) offers additional selections relevant in the current context, such as recently
opened files or the interface (.h) file for an implementation (.m) file you are editing.
!
Previous/next buttons ( ) allow you to step back and forth through your navigation history.
!
Thehierarchical pathmenu(forexample, )
comprises one or more segments. Click a segment to choose from the menu of the items at that level
of the hierarchy.
An example of a basic |ump bar is in the documentation organizer. |t simply allows you to select documents
from installed libraries. Other |ump bars have more components.
A |ump bar may also include a stepper for iterating through a set of files ( ) or issues. |f a lock button
( ) appears, you can click it and authenticate to unlock the file, if appropriate.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
37
Hold down the Option key when selecting an item in the navigation bar to open Assistant and display that
item in the Assistant editor pane. |n the Assistant |ump bar, the path menu is rooted relative to the content
of the regular editor pane, and the root element (flagged with a light-bulb icon) offers selections similar to
a related items menu.
The video shows using the |ump bar to view the class SKTC1Jc1e and then using the Assistant |ump bar
to view its superclasses.
7ip: Hold down the Command key when selecting a level in the path menu to view its items
alphabetically.
Note that every element in the path in the |ump bar is a pop-up menu that you can use to navigate through
your pro|ect. Hold down the Option key when selecting a file in the |ump bar to open Assistant and display
the file in the assistant editor pane (you can change this behavior in the Ceneral pane of Xcode preferences).
The contents of the |ump bar depend on the type of file you're viewing. |n |nterface 8uilder, for example, the
|ump bar lets you navigate to individual interface elements (Pigure 1-18).
Iigure 1-18 The |ump bar in |nterface 8uilder
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
38
The |ump bar also has back and forward buttons for moving through previously viewed files, and a pop-up
menu ( ) that displays a variety of useful information about related items, as shown in Pigure 1-19.
Iigure 1-19 The related items pop-up menu
8rowse to Pro|ect Symbols
Click the Symbol button in the navigator selector bar to browse through the symbols in your pro|ect. Note
that you need to wait until Xcode finishes indexing your pro|ect before you can use this feature.
7e brewse tbe cIass bierarcby
Do one of the following:
!
Display symbols in a hierarchical or flat list using the buttons at the top of the symbol navigator.
Pefine which symbols are displayed using the buttons at the bottom of the navigator. 8uttons are blue
when toggled on and black when off. Use the buttons in any combination:
!
hides symbols other than classes and their members, including protocols, functions, structs,
enums, unions, types, and globals
!
hides symbols defined only in external frameworks, displaying only symbols defined in the
pro|ect or workspace,
!
hides member symbols defined within the classes such as methods, properties, and variables
Purther refine the results list by typing into the filter field at the bottom of the navigator.
Select a symbol to display its header file definition in the source editor.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
39
The screenshot shows one button toggled on and the word "drawing in the filter field. |n the resulting
list, the bez1eJPa1hFoJ0Jaw1hg method is selected and its definition is highlighted in the source
editor.
!
Click an element in the |ump bar to see a list of symbols at that level in the pro|ect hierarchy.
7ip: Hold down the Option key when selecting a file in the |ump bar to open Assistant and display the
file in the assistant editor pane (you can change this behavior in the Ceneral pane of Xcode preferences).
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
40
P|nd Text Strings
Pind text strings in your pro|ect or workspace with the search navigator.
Search a workspace or a find scope for text that matches specific criteria.
7e searcb fer text in prejects and framewerks . . .
1. |n the search field, enter the search term.
2. Specify the find criteria.
3. Specify the find scope.
4. Press Peturn.
5. |f desired, refine the results by entering a filter term in the filter field.
Use the find criteria to specify the style (textual or regular expression), attributes, and capitalization of the
text to find.
Use the find scope to confine your search to a particular location or set of files.
Use a filter term to remove any results that do not match it from the search list.
The screenshot shows the find criteria and find scope areas open, and search results for NSAJJay filtered
by the text c1Jc1e.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
41
7ip: Option-click a search result to see it displayed in the assistant editor pane.
To customize the search, click the magnifying glass in the search field and choose Show Pind Options to get
the Pind Options dialog. ou can specify the type of text and the scope of the search.
Iigure 1-20 The Pind Options dialog
ou can also replace text you've found. See "Peplace Text Strings" (page 215) for details.
view |ssues Discovered by Xcode
The issue navigator lists messages, warnings, and errors that Xcode identifies in your code and your pro|ect,
including issues found by Pix-it, the static analyzer, and the compiler.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
42
when a build fails, the issue navigator opens automatically, displaying all the issues found in the code. Click
an issue to see it displayed in the source editor. ou can also navigate through the issues using the arrows and
pop-up menu in the right end of the source editor |ump bar. See "Locate and Display 8uild |ssues" (page 183)
for more information on the issue navigator.
Iigure 1-21 The issue navigator
Manage 8reakpoints
whereas you set breakpoints in the source editor, the breakpoint navigator (Pigure 1-22) is where you can see
all your breakpoints in one place. |n addition, you use the breakpoint navigator to add conditions and options
to breakpoints.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
43
Por more information on using breakpoints in debugging your code, see "Manage 8reakpoints" (page 188).
Iigure 1-22 The breakpoint navigator
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
44
view Threads and Stacks
when your running code hits a breakpoint (or you use the debug bar in the debug area to pause execution),
the debug navigator shows the current state of the stack in each running thread. Click an itemin the navigator
to see it in your source code and to see the values of variables in the debug area (Pigure 1-23).
Iigure 1-23 The debug navigator and associated editor and debug areas
Por more information on using the debug navigator while debugging your code, see "Lxamine Threads, Stacks,
variables, and Memory" (page 200).
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
45
view 8uild, Source Control, and Debug Session Logs
when you perform an operation that is normally recorded, such as building or analyzing your code, or that
has output to the console, such as a source control operation or a debug session, the record of that operation
is listed in the log navigator. Select an item in the navigator to see the log in the editor pane (Pigure 1-24).
Iigure 1-24 viewing a log
ou can use the filter button and text field at the bottom of the navigator to limit the logs displayed to recent
logs or logs whose names match the text string you enter.
The log viewer has two distinct displays:
!
Por noninteractive tasks, such as building and source control, the log viewer displays a scope bar that you
can use to specify the content to display (see Pigure 1-24).
Successful operations have a checkmark icon next to them. Operations with warnings have a warning icon
(an exclamation mark in a yellowtriangle). Operations with errors have an error icon (an exclamation mark
in a red octagon) next to them. The right side of the operation indicates the number of warnings and
errors the operation produced.
To view an operation's warning or error messages, click the disclosure triangle on the left side of the
operation.
To view an operation's transcript, click the transcript button ( ) on the right side of the operation.
!
Por interactive tasks, such as debugging sessions, the log viewer displays a transcript of the session.
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
46
Pind |nformation that Supplements the Lditor
There are several types of information located in the utility area of the workspace window, including uick
Help, the Pile inspector, |nterface 8uilder inspectors, and libraries of file templates, code snippets, |nterface
8uilder ob|ects, and media files.
To open the utility area, choose view > Utilities, or click the Utility button in the toolbar (Pigure 1-25).
Iigure 1-25 The utility button
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
47
view and Ldit the Properties of Specific |tems
|nspectors are panes in the upper portion of the utility area that you can use to read or enter data about files
and |nterface 8uilder ob|ects, among other things. which inspectors are available depends on which editor
you're using. Compare, for example, the inspectors available for data models (Pigure 1-26) with those for
|nterface 8uilder (Pigure 1-27).
Iigure 1-26 Data model inspectors
Iigure 1-27 |nterface 8uilder inspectors
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
48
Cet Templates, Piles, and |nterface 8uilder Ob|ects
The libraries in the lower portion of the utility area (Pigure 1-28) provide file templates and code snippets that
you can drag into your pro|ect or workspace, user interface elements that you can use in |nterface 8uilder, and
the media files (graphics, sound files, and so forth) used in your workspace. Por more details on the use of the
libraries, see "|ncorporate Piles and Code from the Xcode Libraries" (page 148).
Iigure 1-28 The library pane
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
49
Check on the Progress of Xcode Tasks
The activity viewer in the workspace windowtoolbar shows the progress of any task Xcode is currently executing.
|f two or more tasks are currently underway, a small number appears at the left edge of the activity viewer
(Pigure 1-29). Click the number to open a pop-up window that shows the individual status of each current task
(Pigure 1-30).
Iigure 1-29 The activity viewer
Iigure 1-30 The activity pop-up window
|f there were any issues the last time you built or analyzed your code, an icon in the activity viewer indicates
the number and severity of issues found (Pigure 1-31). Click the issues icon to see the issues in the issue
navigator.
Iigure 1-31 |ssues in the activity viewer
Cet Driented
The workspace window: where ou Cet Most of our work Done
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
50
The Organizer window: Managing Pro|ects, Devices, and
Documentation
Xcode has two main windows. ou've seen the workspace window (Pigure 1-2 (page 16)), used for editing,
debugging, andinterface design. The other mainwindow, calledthe Oton|zet w|nJow, displays documentation,
source control, pro|ect organization, and for iOS, access to your mobile devices. To display the Organizer
window, choose window > Organizer, or click the Organizer button in the toolbar (Pigure 1-32).
Iigure 1-32 The Organizer button
8rowse and 8ookmark Documents
To browse documentation, open the Organizer window, click the Documentation button in the toolbar, and
click the 8rowse button at the top of the navigation pane (Pigure 1-33).
Iigure 1-33 The documentation navigator
Cet Driented
The Organizer window: Managing Pro|ects, Devices, and Documentation
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
51
while reading any page of documentation, you can choose Lditor > Add 8ookmark or Control-click and choose
Add 8ookmark for Current Page to bookmark that page. Click the 8ookmark button in the navigator pane to
see a list of bookmarks (Pigure 1-34).
Iigure 1-34 The bookmarks navigator
To select which documentation sets to download, use the Downloads pane in Xcode preferences.
7e set decumentatien preferences
!
Set preferences for updating developer documentation using the Documentation tab of the Downloads
preferences pane.
Documentation is installed in the form of documentation sets, often called Joc sets . Apple doc sets for
key developer libraries are installed with Xcode, and access to updates for them is controlled by
subscription. Por your convenience, Xcode can automatically keep these subscriptions up to date. This
feature is controlled by the option "Check for and install updates automatically, which is selected by
default. |f this option is selected, Xcode displays the date and time of the last check.
Cet Driented
The Organizer window: Managing Pro|ects, Devices, and Documentation
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
52
To check for updates manually, click the Check and |nstall Now button. |f no new updates are available,
Xcode displays a message to that effect. when an update for a doc set is available but not yet installed
on your system, Xcode displays an |nstall button on the subscription line for that doc set. Click that
|nstall button to download and install the updated doc set on your system.
To install non-Apple documentation, subscribe to the associated documentation feed. Pirst, obtain the
web (PSS) feed UPL from the publisher. Click the Add (+) button, as shown in the figure, follow the
onscreen instructions to enter the UPL, and click Add in the dialog.
To remove a doc set from your system, select the subscription entry for the doc set, then click the doc
set info button. Click the |nstalled Location link to show the doc set file in the Pinder, then delete the
file from the Pinder.
To unsubscribe from non-Apple documentation, select the subscription entry for the doc set, click the
Pemove (-) button and confirm the removal operation.
Note: ou can remove an Apple doc set from your system, but you cannot remove the subscription to
its doc set feed.
At the bottom of the pane, you can set a minimum font size for documentation organizer content by
selecting the option "Never use font sizes smaller than," and then choosing a font size fromthe pop-up
menu.
Cet Driented
The Organizer window: Managing Pro|ects, Devices, and Documentation
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
53
8rowse for Task-8ased Help
Online help is available for the Xcode |DL. To browse the Xcode online help, open the Xcode 4 Developer Tools
Library in the documentation navigator, then open Tools and Languages, then |DLs (Pigure 1-33 (page 51)),
or choose Help > Xcode Help to get the start screen shown in Pigure 1-35.
Iigure 1-35 Xcode help start screen
Many of the articles in Xcode help include a short video that illustrates the described procedure. Click the video
thumbnail to play the video.
To help you discover and understand the many user interface features of Xcode, most of the help articles are
also available as contextual help. See "Contextual Help: our Shortcut to Answers" (page 15) for details.
work with our Source Control Pepositories
Click the Pepositories button in the Organizer window toolbar to work with your source control repositories.
ou can create local repositories, connect to and manage repositories on servers, and so forth. ou can also
performmany common SCMoperations, such as submitting files, fromthe workspace window. To do so, select
the file or files in the pro|ect navigator, Control-click, and choose Source Control from the menu. See "Keep
Track of Changes with Source Control " (page 253) for details.
Cet Driented
The Organizer window: Managing Pro|ects, Devices, and Documentation
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
54
Organize our Pro|ects and Devices
whereas Xcode allows you to have several workspace windows open simultaneously, there is only one Organizer
window. The Organizer window displays information for all your workspaces, pro|ects, repositories, devices,
and documentation, regardless of how many pro|ects you have and how many are open.
Click the Pro|ects button in the toolbar to display all your pro|ects, their snapshots, and archives.
|f you're working with iOS, the Xcode Organizer window also can display the devices that you have connected
to your computer. |t indicates which of these devices are currently available and lets you select the one to use.
Por more information on the use of iOS devices with Xcode, see "Manage our Devices" (page 225).
Take a Snapshot of our Pro|ect
To save a snapshot of your pro|ect, choose Pile > Create Snapshot. Note that you must have selected System
Tools in the Xcode installer in order to use snapshots. System Tools are selected by default.
To see what snapshots have been saved in Xcode, open the pro|ects organizer and click the pro|ect in which
you're interested. Por more information on snapshots, see "Take a Snapshot of our Pro|ect" (page 252).
Cet Driented
The Organizer window: Managing Pro|ects, Devices, and Documentation
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
55
This chapter tells you how to start a new Xcode 4 pro|ect, either by creating a new pro|ect from scratch, or by
opening an existing Xcode 3 pro|ect. Once you've got your pro|ects open, go to "Cet Oriented" (page 15) to
learn more about using Xcode 4.
Click New Pro|ect in the Xcode 4 Startup Screen to Create a
Standalone Pro|ect
|f you want to start a new software development undertaking using Xcode 4, you need to first decide whether
you need a single Xcode pro|ect or multiple related pro|ects. Por a simple application or utility, a single pro|ect
should suffice. However, if you have several related executables that need to link against a custom library, you
probably want at least a separate pro|ect for the library and another for the executables, and possibly a separate
pro|ect for each executable.
Start developing a software product by creating a pro|ect. All software products require a pro|ect. The pro|ect
organizes the files and resources needed to build one or more products, such as applications, plug-ins, and
command-line tools.
7e create a standaIene preject . . .
1. Choose Pile > New > New Pro|ect.
2. Select the pro|ect template for your iOS or OS X product, and click Next.
3. Lnter the product name and other pro|ect details, and click Next.
4. Specify the pro|ect's location in your file system, and click Save.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
56
Start a Pro|ect
The New Pro|ect dialog displays platforms, template families, pro|ect templates, and a description for the
selected pro|ect template. |n the pro|ect options pane you enter information required by the template to
generate the pro|ect, such as the product name.
Nete: The New Pro|ect dialog appears in the workspace window for the workspace to which
Xcode will add the pro|ect. when you create a pro|ect with no workspace window active, the
New Pro|ect dialog is attached to a new workspace window that contains only the new pro|ect.
The pro|ect location in your file system and its container in the workspace window are both derived from
your selection in the pro|ect navigator when you initiated the New Pro|ect command. That is, if you have
a pro|ect selected in the pro|ect navigator, Xcode places the new pro|ect inside the selected pro|ect. The
Save dialog lets you specify a different location and container for the new pro|ect before completing the
operation. Por example, you can indicate that the container of the pro|ect be a group within your workspace
instead of the workspace itself.
The video shows how to create a pro|ect named MyPro|ect and place the pro|ect directory on the Desktop.
After saving the pro|ect, Xcode places a folder containing the newpro|ect's files at the location you specified.
Once you've created a pro|ect, you can add new source files and begin writing code.
|f you have two or more closely related pro|ects, you should create a workspace and add your pro|ects to it, as
described in "Create a workspace to work with Multiple Pelated Pro|ects" (page 59).
Start a Preject
Click New Pro|ect in the Xcode 4 Startup Screen to Create a Standalone Pro|ect
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
57
Create a Cit Pepository Por our New Pro|ect
ou can create a local Cit repository when you save the new pro|ect (Pigure 2-1). This is the easiest way to add
source control to a pro|ect (see "Keep Track of Changes with Source Control " (page 253) for more information).
Iigure 2-1 The option to add source control when creating a pro|ect
Select Options while Creating a New Pro|ect
8oth Mac OS X and iOS support use of the Core Data frameworks. To add core data modeling to your new
pro|ect, select the Use Core Data option in the NewPro|ect dialog. See "Design Data Models Craphically" (page
26) for more information.
Start a Preject
Click New Pro|ect in the Xcode 4 Startup Screen to Create a Standalone Pro|ect
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
58
ou can also choose to use automatic reference counting, include unit tests, or include Spotlight |mporter in
your pro|ect (Pigure 2-2). The files that Xcode creates for your new pro|ect depend on the options you select
in the new pro|ect dialogs.
Iigure 2-2 Options for a new pro|ect
Note that Core Data is an advanced technology that is not required for creating simple applications.
To add automatic reference counting (APC) to an existing pro|ect, see "Add Automatic Peference Counting" (page
64).
Create a workspace to work with Multiple Pelated Pro|ects
A ma|or feature of Xcode 4 is the ability to create a container for multiple pro|ects that you can use to group
Xcode pro|ects and other files that are related. This container is referred to as an \coJe wotlsoce . All the
pro|ects in the workspace share the same build directory. Putting your related pro|ects in the same workspace
affords you several benefits, including:
!
One pro|ect can use the products of another pro|ect while building.
!
|f one pro|ect depends on the products of another in the same workspace, Xcode can detect this and
automatically build the pro|ects in the correct sequence.
!
8ecause all the files in one pro|ect are visible to all the other pro|ects in the workspace, you don't need to
copy shared libraries into each pro|ect folder separately.
Start a Preject
Create a workspace to work with Multiple Pelated Pro|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
59
!
|ndexing is done across the entire workspace, extending the scope of content-aware features such as code
completion.
7e create a werkspace
1. |f Xcode is not open, open it. ou can ignore or cancel the startup screen. |f you already have an Xcode
pro|ect open, go on to the next step.
2. Choose Pile > New > New workspace.
3. |n the Newworkspace dialog, specify the location for the workspace file and the name of the workspace.
|f your pro|ects are in the same directory, it might be convenient to put the workspace file in there as
well. Click Save.
7ip: To avoid possible confusion with your pro|ects, give the workspace a unique name.
ou now have a workspace with no pro|ects in it. ou can add existing pro|ects to the workspace, or create
new ones.
ou can add any existing pro|ect to the workspace, or Control-click in the structure navigator oelow the existing
pro|ects and select New Pro|ect to create a pro|ect in the workspace.
Start a Preject
Create a workspace to work with Multiple Pelated Pro|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
60
Add an existing pro|ect to a workspace to add a product to a multiproduct development endeavor. when you
need to work on two or more related pro|ects, you can add them to a workspace so that you can create
interpro|ect relationships.
7e add an existing preject te a werkspace . . .
1. |n the pro|ect navigator, Control-click in the empty space below the list.
2. Choose Add Piles to "<workspaceName>.
3. Navigate into the folder containing the pro|ect package.
4. Select the pro|ect package and click Add.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
Por example, you can have a workspace with an application pro|ect, add a framework pro|ect to the
workspace, and make the application dependent on the framework. when you build the application, Xcode
builds the library first, if it needs to be built.
when adding a pro|ect to a workspace, you add the pro|ect package. A preject package is a directory that
the Pinder displays as a file. |t contains information about the pro|ect, such as references to the files that
are part of the pro|ect, the pro|ect's groups, build settings, and target definitions.
The video shows the process of adding a second pro|ect, called MyPramework, to a workspace called
Myworkspace.
After you add a pro|ect to your workspace, the pro|ect appears in the pro|ect navigator.
Start a Preject
Create a workspace to work with Multiple Pelated Pro|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
61
AIternative: ou can drag a pro|ect package from a Pinder window or a workspace window to
the pro|ect navigator in a workspace window to add the pro|ect to the second workspace. when
doing so, ensure that you add the pro|ect package to the root of the pro|ect navigator and not
a pro|ect within it.
Nete: |f you choose Pile > New > New Pro|ect while any pro|ect is selected, or Control-click inside
an existing pro|ect and choose NewPro|ect, Xcode adds the pro|ect file |ns|Je the currently selected
pro|ect. The only way to undo this operation is to delete the new pro|ect. Pigure 2-3 shows the
shortcut menu you get when you Control-click below the existing pro|ects. Note that, in this case,
the Add Piles menu item specifies the name of the workspace, not of one of the existing pro|ects.
Iigure 2-3 A shortcut menu for a workspace
8ecause each pro|ect retains its individual identity, a pro|ect can be included in more than one workspace or
removed from a workspace without affecting the pro|ect. The workspace file itself merely contains pointers to
the pro|ects and other files that the workspace includes, plus a minimal amount of data such as schemes stored
in the workspace. The pointers to the source files, included libraries, build configurations, and other data are
stored in the pro|ect files.
Start a Preject
Create a workspace to work with Multiple Pelated Pro|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
62
7ip: |f you have an Xcode pro|ect and would like to create a workspace to contain it, choose Pile > Save as
workspace. ou can assign a new name to the workspace and specify a location for the workspace file. Doing so
does not alter the original pro|ect or prevent you from adding the pro|ect to another workspace as well.
|f the build product of one pro|ect in a workspace is dependent on the build product of another pro|ect in the
workspace (for example, if one pro|ect builds a library used by the other pro|ect), Xcode discovers such implicit
dependencies and builds in the correct sequence. |f you don't want one pro|ect to use the product or files in
another pro|ect that's in the same workspace, you need to ad|ust your build settings accordingly. See "To add
a new build configuration" (page 66) for help in finding and understanding the build settings interface in
Xcode.
8efore you build, be sure you've created the scheme or schemes you need. See "Create, Ldit, and Manage
Schemes" (page !) for more information on schemes.
Check Out a working Copy from our Source Control Pepository
|f your Xcode pro|ect is in a Cit or Subversion repository, you can check out your pro|ect from the repository
and open it in Xcode. See "Keep Track of Changes with Source Control " (page 253) for more information on
using source control in Xcode.
Modernize our Pro|ect
when you open a pro|ect, Xcode 4 evaluates it to see whether there are any settings that should be updated.
This feature provides an easy way to make sure your pro|ects conform to the latest SDKs and best practices.
Open the issue navigator (Pigure 2-4) to see whether anything in your pro|ect needs to be updated. ou can
also select the pro|ect in the pro|ect navigator and choose Lditor > Check for Outdated Settings, or choose
the pro|ect from the the drop-down issues menu at the right end of the |ump bar.
Iigure 2-4 Modernization in the |ssue navigator
Start a Preject
Check Out a working Copy from our Source Control Pepository
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
63
|f the issue navigator lists modernization issues, click the issue to see a dialog that explains the updates that
should be made (Pigure 2-5). Deselect any checkboxes for settings you don't want to change, then click Perform
Changes to update the pro|ect to optimize it for Xcode 4.
Iigure 2-5 Updates dialog
After you have clicked Perform Changes, whether you choose to make all the changes or not, Xcode does not
show the warning again. To rerun the check, select your pro|ect in the pro|ect navigator and choose Check for
Outdated Settings from the Lditor menu.
Add Automatic Peference Counting
Xcode 4.2 and later includes a menu item to convert existing targets to use Automatic Peference Counting
(APC), which automates memory management for Ob|ective-C ob|ects. APC makes memory management
much easier, greatly reducing the chance that your program will have memory leaks. Pirst, Xcode reviews your
pro|ect to determine whether there are items that cannot be converted (and that you must therefore change
manually). Then, Xcode rewrites your source code to use APC. (To add APC to a newpro|ect, see "Select Options
while Creating a New Pro|ect" (page 58).)
To initiate the process, enable Continue building after errors in the Ceneral Preferences pane, then choose
Ldit > Pefactor > Convert to Ob|ective-C APC. The targets that you convert are updated to build using the
Apple LLvM compiler. Xcode attempts to build your target and to determine what changes must be made to
Start a Preject
Add Automatic Peference Counting
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
64
use APC. |f it finds any issues that prevent conversion, Xcode displays a dialog directing you to review the
errors in the |ssue navigator. After you correct the errors, choose the Convert to Ob|ective-C Automatic Peference
Counting menu item again to restart the APC-conversion workflow.
when Xcode successfully builds your application, it takes a snapshot of the current code so that you can revert
later if you want to. Then Xcode displays a preview dialog showing the changes it's going to make. when you
accept the changes, Xcode converts your code to use APC.
Por more information on APC, see !tons|t|on|n to AkC keleose Notes .
Close a Pro|ect or a workspace
Choose Close Pro|ect or Close workspace from the Pile menu to close a pro|ect or workspace without closing
Xcode. |n Xcode 4.1 and later, Xcode remembers which windows you had open and howthey were configured,
and restores them when you reopen the pro|ect or workspace. Also in Xcode 4.1 or later, pressing
Command-Option-wor holding down the Option key and clicking the close box closes the pro|ect or workspace
without first closing all windows and tabs. |n this way, your window configuration is restored the next time
you open the pro|ect.
Start a Preject
Close a Pro|ect or a workspace
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
65
During the course of developing an application, you need to build, run, and debug your code. As part of
optimizing your code and ensuring quality control, you might also run unit tests, perform static analysis, and
use profiling tools to find memory leaks, inefficient routines, and other run-time problems. Pinally, you'll
probably want to archive your application in order to share it with others or submit it for inclusion in the App
store.
|n order to carry out all these actions, you need to edit a few basic build settings and set up one or more
schemes to specify the targets, build configuration, and executable configuration to use for each type of action.
|n Xcode you use the pro|ect editor and the scheme editing dialog to customize your builds and control what
happens when you build and run your code.
Add 8uild Configurations
when you create a pro|ect, Xcode provides two build configurations: Debug and Pelease, which differ primarily
in the inclusion of debug information and in the degree to which the build is optimized. ou might want to
add more build configurations, for example, you might want a build that's fully optimized but that includes
debug information in order to debug the optimized code.
7e add a new buiId cenfiguratien
1. Select the pro|ect in the pro|ect navigator to open the pro|ect editor.
2. Select the pro|ect in the pro|ect editor and click the |nfo button.
3. Lxpand the Configurations section in the |nfo pane and click the Add (+) button at the bottom of the
section.
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
66
Configure our Pro|ect
4. Select one of the existing configurations from the pop-up menu as a starting point for the new
configuration.
5. Select the name of the copy and type your preferred name for the configuration.
Cenfigure eur Preject
Add 8uild Configurations
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
67
6. Click the 8uild Settings button to display the build settings for the pro|ect.
7. To change the build settings in the new configuration for all the targets in the pro|ect, edit them at
the pro|ect level. To change the build settings for an individual target, select that target.
8. Select each build setting you want to edit and click the disclosure triangle to display the list of build
configurations.
9. Select the new configuration and edit the setting.
ou can use a build configuration file to set and to share build configurations. A build configuration file is a
plain text file with the filename extension .xccoh11g that contains a list of build setting definitions, one per
line. The build configuration file must be in your pro|ect.
Configure a uniform set of build setting definitions across any number of targets or pro|ects by using a
configuration file. A configuration file is a plain text file with a list of build setting definitions, one per line. ou
can base a build configuration only on a configuration file that is in your pro|ect, not on an external file.
7e base a buiId cenfiguratien en a cenfiguratien fiIe . . .
1. |n the pro|ect editor, select the pro|ect for which you want to use a build configuration file.
2. Click |nfo at the top of the pro|ect editor.
3. |n the Configurations section, navigate to the build configuration you want to base on a configuration
file.
Cenfigure eur Preject
Add 8uild Configurations
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
68
4. Choose a configuration file from the pop-up menu in the right column.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
when you base a target or pro|ect's build configuration on a configuration file, that build configuration
automatically inherits the build setting definitions in that configuration file (and any configuration files it
includes). |f you then modify the value of any of those build settings in the target or pro|ect, the new value
is used instead of the value in the configuration file.
8uild settings defined at the target level override any values assigned to those build settings at the pro|ect
level. Therefore, target-level configurations take precedence over any pro|ect-level configurations.
The video shows basing the Debug build configuration on a file called Coh11g.xccoh11g at the pro|ect
level.
Set the 8asic 8uild Settings
when you create a new pro|ect, it includes one or more targets, where each target specifies one build product
and the instructions for how the product is to be built. ou can use the pro|ect editor to specify every aspect
of the build, from the version of the SDK to specific compiler options.
Most developers never need to change the default of the vast ma|ority of the build settings. However, there
are a few basic settings that you must check, and possibly edit, for each target. These settings are gathered
into one pane in the pro|ect editorlabeled the Summary paneand are somewhat different for Mac OS X
and iOS pro|ects.
7e edit tbe basic buiId settings fer Mac DS X targets
1. |n the pro|ect editor, click the target.
Cenfigure eur Preject
Set the 8asic 8uild Settings
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
69
2. At the top of the pro|ect editor pane, click the Summary button.
3. To select an icon for your product, Control-click the App |con image well and choose Select Pile (or
drag an icon file directly to the image well).
4. To add a linked framework or library to your target, click the Add (+) button at the bottomof the Linked
Prameworks and Libraries section.
Por example, to provide your target with access to audio hardware, add the Core Audio framework.
Lach setting in the Summary pane is also found in one of the other panes. when you edit a setting, Xcode
updates the other pane automatically. Table 3-1 lists each setting in the Mac OS X Summary pane along with
the corresponding target setting and location.
7abIe 3-1 Mac OS X pro|ect editor Summary pane settings
Pane 7arget setting Summary pane setting
|nfo 8undle identifier |dentifier
|nfo 8undle version version
Cenfigure eur Preject
Set the 8asic 8uild Settings
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
70
Pane 7arget setting Summary pane setting
8uild Settings Mac OS X Deployment Target This app runs on Mac OS X
|nfo Main nib file base name Main interface
|nfo |con file App icon
8uild Phases Link 8inary with Libraries Linked frameworks and libraries
7e edit tbe basic buiId settings fer iDS targets
1. |n the pro|ect editor, click the target.
2. At the top of the pro|ect editor pane, click the Summary button.
3. Select an icon for your app.
Cenfigure eur Preject
Set the 8asic 8uild Settings
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
71
Control-click one of the App |cons image wells and choose Select Pile (or drag an icon image into the
image well).
4. Select a launch image.
Control-click one of the Launch |mages image wells and choose Select Pile (or drag an image into the
image well). ou can drag a launch image directly from the Screenshots library in the Devices pane of
the Organizer window.
5. Choose a target device from the Devices pop-up menu.
Choose Universal to configure your iOS app to run on both iPhone and iPad.
As for Mac OS X pro|ects, each setting in the Summary pane for an iOS pro|ect is also found in one of the other
panes. when you edit a setting, Xcode updates the other pane automatically. Table 3-2 lists each setting in
the iOS Summary pane along with the corresponding target setting and location.
7abIe 3-2 iOS pro|ect editor Summary pane settings
Pane 7arget setting Summary pane setting
|nfo 8undle identifier |dentifier
|nfo 8undle version version
8uild Settings Targeted Device Pamily Devices
8uild Settings iOS Deployment Target This app runs on iOS
|nfo Main nib file base name Main |nterface
|nfo Supported interface orientations Supported Device Orientations
|nfo |con files App |cons
|nfo Launch |mage Launch |mages
Add 8uild Pules
Xcode processes your source files according to the file type using a set of built-in rules. Por example, property
list (plist) files are copied into the product using the CopyPlistPile script located in the Xcode directory.
Cenfigure eur Preject
Add 8uild Pules
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
72
7e see tbe defauIt buiId ruIes fer a target
1. Select the pro|ect in the pro|ect navigator.
2. |n the pro|ect editor, select the target and click the 8uild Pules button.
8ecause Xcode sets build rules on a per-target basis, no build rules are displayed when you select the
pro|ect rather than a target.
3. At the top left of the 8uild Pules pane, click the All button.
7e custemize a buiId ruIe fer a target
1. Display the default build rules for the target ("Add 8uild Pules" (page 72)).
2. At the right margin of the build rule you wish to customize, click the Copy to Target button.
3. Pill in the build rule template that appears.
Cenfigure eur Preject
Add 8uild Pules
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
73
4. Click the Target button at the top of the 8uild Pules pane to see and edit the customized build rules
you've added.
ou can click the Add 8uild Pule button at the bottom of the 8uild Pules pane to create a new build rule.
Change the way files are processed with build rules.
7e add a buiId ruIe . . .
1. |n the pro|ect editor, select the target to which you want to add a build rule.
2. Click 8uild Pules at the top of the pro|ect editor.
3. Select Target at the top of the 8uild Pules pane.
4. Click Add 8uild Pule in the lower-right corner.
5. Choose a file type from the Process pop-up menu.
Cenfigure eur Preject
Add 8uild Pules
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
74
6. Choose a compiler from the Using pop-up menu.
ou can define build rules on a per-target basis. Target-specific build rules can specify files that the system
build rules do not directly address and can override the existing system build rules, which are predefined
and unmodifiable.
The Process and Using menus include many types of files and many compilers, but you can specify custom
file types or compilers by choosing "Source files with names matching: from the Process menu or "Custom
script: from the Using menu.
The screenshot shows a build rule that compiles C source files with CCC 4.2 rather than the default compiler.
Cenfigure eur Preject
Add 8uild Pules
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
75
ou design user interfaces in Xcode using |nterface 8uilder. |nterface 8uilder is an Xcode editor that provides
a graphical interface for the creation of user interface files. Like other Xcode editors, |nterface 8uilder is fully
integrated into the application, so you can write and edit source code and tie it directly to your user interface
without leaving the Xcode workspace window.
when you create a new Mac OS X or iOS application, Xcode includes one or more |nterface 8uilder files in the
pro|ect. These files, called nib files, may have the filename extension h1b or x1b. Similarly, when you create a
new view controller, Xcode includes a nib file along with the header and implementation files for the new
class. Por iOS applications, you can use storyboards instead of nib files, as described in "Design the User |nterface
of our iOS App with Storyboards" (page 92).
Create our User |nterface
|nterface 8uilder, like other Xcode editors, has associated inspectors and libraries in the utility area. |nterface
8uilder appears in the editor area of the workspace window when you select a nib file or storyboard file in the
pro|ect navigator. when you open a nib or storyboard file, your user interface ob|ects appear in the editor area
and the |nterface 8uilder inspectors appear in the utility area. ou use these inspectors to configure the interface
ob|ects and to make connections between them. The Ob|ect and Media libraries in the library pane of the
utility area are also for use with |nterface 8uilderyou use these libraries to add new ob|ects to your user
interface design.
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
76
Ldit User |nterfaces
Pigure 4-1 shows |nterface 8uilder and associated panes open in the workspace window. ou can select |nterface
8uilder ob|ects and media files in the library pane and drag them onto the |nterface 8uilder canvas. ou can
also open an assistant editor, which shows a file or files associated with whatever ob|ect you've selected in the
|nterface 8uilder pane.
Iigure 4-1 |nterface 8uilder in the workspace window
dit User Interfaces
Create our User |nterface
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
77
Display our User |nterface Ob|ects
The dock on the left side of the |nterface 8uilder pane shows the |nterface 8uilder ob|ects and placeholders in
your nib or storyboard file. The dock can display the high-level ob|ects in an icon view (Pigure 4-2) or in a list
(called the outl|ne v|ew) showing all the ob|ects nested in higher-level ob|ects. Storyboard files show only the
outline view in the dock, however, each scene in the storyboard has its own scene dock displayed below it
when you select the scene (see, for example, Pigure 4-11 (page 95)).
Iigure 4-2 |con view for placeholders and ob|ects in |nterface 8uilder
Add new ob|ects to an |nterface 8uilder document using the outline view, a hierarchical tree that reflects the
parent-child relationships between the ob|ects in the nib file.
7e add an ebject using tbe eutIine view . . .
1. with a nib file open, toggle the dock to outline view, if necessary, by clicking the dock mode button
at the bottom of the dock.
2. Navigate to the place in the outline where you want to add the ob|ect.
dit User Interfaces
Create our User |nterface
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
78
3. Drag an ob|ect from the Ob|ect library (in the utility area) into the outline.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
The video shows how to add a text formatter ob|ect to a text field cell using the outline view.
7ip: To return to the icon view, click the dock mode button ( ) again.
Note that you can also use the |nterface 8uilder |ump bar to select any ob|ect in the interface.
Connect to Other Piles Using Placeholder Ob|ects
There are two kinds of ob|ects displayed in the |nterface 8uilder dock: |nterface ob|ects and placeholder ob|ects.
Interface ebjects are the ob|ects that are actually created when the nib file is loaded and typically comprise
the bulk of the ob|ects. PIacebeIder ebjects refer to files that live outside of the nib file but which are intimately
tied to the contents of the nib file. There are normally three placeholder ob|ects in a nib file:
!
Pile's Owner
!
Pirst responder
!
Application
Pile's Owner
Pile's Owner Pepresents the nib file's controller ob|ect. Pile's Owner is the most commonly used placeholder
ob|ect in nib files and is supported by both Mac OS X and iOS nib files. The Pile's Owner placeholder is the
main bridge between your application and the contents of the nib file.
when you build and run your application, the nib-loading code substitutes the ob|ect that is the file's owner
for any references to the Pile's Owner placeholder in the nib file. This substitution results in the outlets and
actions connected to the Pile's Owner placeholder being connected to the ob|ect that is the file's owner.
ou can designate any ob|ect in your application as the Pile's Owner of a nib file. ou tell |nterface 8uilder the
class of the Pile's Owner so it knows what connections to make available. Typically, the file's owner is a controller
class that manages the interactions with the views and other controller ob|ects inside the nib file.
dit User Interfaces
Create our User |nterface
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
79
7e cenfigure tbe IiIe's Dwner pIacebeIder
1. Select the Pile's Owner placeholder ob|ect in the |nterface 8uilder dock
2. Open the |dentity inspector.
3. |n the Class field of the Custom Class section, set the class of the Pile's Owner to the corresponding
class in your application.
The following table lists some of the standard classes that are commonly used to represent Pile's Owner
in applications:
Descriptien Dperating
System
SubcIass ef
Document-based applications store the document
window and other required interface ob|ects in a
nib file. The Pile's Owner of this nib file is
traditionally the document ob|ect itself.
Mac OS X NS0ocumeh1
window controllers provide a great deal of
automatic management for nib files and are
especially useful when your nib file contains only
one window.
Mac OS X NSW1hdowCoh1Jo11eJ
Aviewcontroller manages customaccessory views
and other view-based content.
Mac OS X NSv1ewCoh1Jo11eJ
AcustombTv1ewCoh1Jo11eJ ob|ect is often used
to manage the content view for a distinct screen's
worth of content. A U| view controller provides
automatic nib-loading and purging support.
iOS bTv1ewCoh1Jo11eJ
ou can use practically any ob|ect you like for
manual control of a nib file. |t is up to you to define
the relationships between this class and the ob|ects
in your nib file.
Mac OS X
or iOS
Any custom NS0bec1
subclass
4. Control-click the Pile's Owner ob|ect to see the outlets and actions defined by that class.
To learn about outlets and actions, see "Manage Connections 8etween User |nterface Ob|ects" (page 106).
ou can use these outlets and actions to connect other ob|ects to Pile's Owner. ou can use Pile's Owner
as a target for your bindings. Por information about connecting to Pile's Owner, see "Make Connections
Directly 8etween |8 Ob|ects and our Code Piles" (page 107).
dit User Interfaces
Create our User |nterface
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
80
Pirst Pesponder
The Pirst Pesponder placeholder ob|ect represents the first ob|ect in the responder chain, which is determined
dynamically at runtime by the AppKit and U|Kit frameworks.
7e add new actien messages te tbe first respender's supperted Iist
1. Select the Pirst Pesponder placeholder ob|ect in your |nterface 8uilder document.
2. Open the Attributes inspector.
3. Click the Add (+) button at the bottom of the User Defined section to create a new action method
entry.
4. Double-click the method name in the Action column and type the name of the method.
5. Select the class in which the method will be defined from the pop-up list in the Type column.
6. After you are done making connections in |nterface 8uilder, add the code for the method to the header
and implementation class files in your pro|ect that you specified in step 5.
The name of the method must match the name specified in step 4.
Adding action methods to the Pirst Pesponder placeholder ob|ect does not add the corresponding method
definition to your Xcode source files. All it does is let Xcode know that such a method exists in one of the
ob|ects in the responder chain of your pro|ect. |t is up to you to ensure the method names you add to the
Pirst Pesponder placeholder match the names of the methods in your code. Xcode does not validate these
method names for you. At runtime, if a method name is misspelled or does not exist in an ob|ect, the
corresponding action message is never received by the target ob|ect.
|nterface 8uilder does not prevent you from deleting the standard system messages associated with the
Pirst Pesponder placeholder. Doing so removes the message name from the current nib file only.
when Mac OS X or iOS sends a message to your application, the message is sent to your application's first
responder. The first responder is typically the currently selected ob|ect or the ob|ect with the current focus in
the frontmost window. ou use the Pirst Pesponder ob|ect to make connections to any messages that operate
on the current selection or need to be handled by your frontmost window or document. Por example, if you
wanted a menu command to be handled by your frontmost window, you would dispatch that command to
your Pirst Pesponder ob|ect.
The Pirst Pesponder placeholder displays all of the actions that are either supported natively by the operating
system or defined in your Xcode source files.
dit User Interfaces
Create our User |nterface
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
81
Nete: The Pirst Pesponder placeholder is only for configuring action messages. ou cannot connect
the Pirst Pesponder placeholder ob|ect to one of your custom outlets in hopes of receiving a
dynamically changing pointer to the selected ob|ect in your window. |n Mac OS X applications, you
should instead use the 11Js1RespohdeJ method of the current NSW1hdow ob|ect to get the first
responder. |n iOS applications, there is no single first responder ob|ect, the first responder is always
the view that is the target of a touch.
Application
|n Mac OS X nib files, the Application placeholder ob|ect gives you a way to connect the outlets of your
application's shared NSApp11ca11oh ob|ect to custom ob|ects in your nib file. The default application ob|ect
has outlets for its delegate ob|ect and, in Mac OS X applications, the application menu bar. |f you define a
custom subclass of NSApp11ca11oh, you can connect to any additional outlets and actions defined in your
subclass.
At load time, the nib-loading code automatically replaces the Application placeholder ob|ect with the shared
application ob|ect from your application.
Select Hidden Ob|ects in an |nterface Pile
|n Xcode, you can usually select an ob|ect in a nib or storyboard file by clicking it directly from the |nterface
8uilder canvas. Many ob|ects are compound, however, such as a text field that contains a number formatter.
7e seIect a bidden UI ebject using tbe deck
1. Lxpand the dock to show the outline view.
2. Use the disclosure triangles to open the ob|ects containing the ob|ect you want to select.
dit User Interfaces
Create our User |nterface
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
82
3. Select the ob|ect in the outline view.
7ip: ou can make connections directly between the ob|ect in the dock and source code or other ob|ects.
7e seIect a bidden UI ebject using tbe jump bar
1. |f the top-level window or U| ob|ect is not already displayed on the |nterface 8uilder campus, select
the window or ob|ect in the dock.
2. with the U| design displayed on the |nterface 8uilder canvas, select an ob|ect in the |ump bar that
contains the ob|ect you want to select.
7ip: ou can select the top-level ob|ect or any ob|ect in the hierarchy that contains the target
ob|ect. ou cannot navigate to a hidden U| ob|ect in the |ump bar by selecting the nib file itself.
dit User Interfaces
Create our User |nterface
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
83
3. Navigate through the chain of pop-up menus to the ob|ect you want to select.
Lay Out User |nterface Controls Using Content-Driven Pules
|nterface 8uilder supports the AppKit Auto Layout feature. Auto Layout, available starting with Mac OS X v10.7
Lion, uses relationships called constto|nts to govern the layout of ob|ects in the user interface. This feature is
a complete replacement for the autoresizing mask. As you make changes to any view or control in |nterface
8uilder (move it around, resize it, change an attribute, add a subview, and so forth), |nterface 8uilder
automatically adds and removes constraints based on the new layout. when you enable this feature, |nterface
8uilder shows the constraints as you work, as shown in Pigure 4-3.
dit User Interfaces
Lay Out User |nterface Controls Using Content-Driven Pules
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
84
Nete: Auto Layout is available only in Mac OS X v10.7 Lion and later. |f you are running Xcode 4 in
Mac OS X v10.6 Snow Leopard, Auto Layout is not available.
Iigure 4-3 Auto Layout
ou must enable Auto Layout per nib.
7e enabIe Aute Layeut
!
Select the Use Auto Layout checkbox in the Pile inspector for each nib.
|f you are converting many nib files, you can select all of the nib files at the same time (use the Pro|ect
Navigator to filter for x1b or h1b) and enable Auto Layout for all of them at once.
when you enable Auto Layout, Xcode updates your build settings, if necessary, to ensure your deployment
target is Mac OS X v10.7 or greater. Por nib files in pro|ects that had been targeted for Mac OS X v10.6 or
earlier, |nterface 8uilder adds constraints to your nib files automatically when you enable Auto Layout.
|nterface 8uilder treats constraints like other ob|ects in a nib file. Like other ob|ects, the constraints for a view
are visible in three places:
7e see tbe censtraints in a view
Do one of the following:
dit User Interfaces
Lay Out User |nterface Controls Using Content-Driven Pules
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
85
!
|n the |ump bar, select the ob|ect that contains the constraint.
!
Select a ob|ect on the canvas.
!
Open the |8 dock to the outline view.
All the constraints are grouped, listed, and selectable in the outline view of the dock.
dit User Interfaces
Lay Out User |nterface Controls Using Content-Driven Pules
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
86
Add New Constraints
Constraints are selectable. when you select a constraint, you can use the Attributes inspector to change its
attributes and you can make connections from or to it. ou can also select multiple constraints.
ou specify constraints in terms of leading or trailing edges and top or bottom rather than left and right or
X, values. Leading and trailing edges can be localized for languages that read right-to-left, and specifying top
or bottom avoids the possible confusion caused by coordinates that are y-down (minimum y value on top)
versus y-up (minimum y value on bottom).
Apple encourages you to use standard aqua spaces for your spacings. |nterface 8uilder snaps to these spacings
when you are dragging or resizing views in the canvas.
7e set standard spacing fer a censtraint
1. Select the constraint.
2. |n the Attributes inspector, select the Standard checkbox.
ou can edit an automatic constraint or add your own.
7e add a censtraint
1. Select the ob|ect or ob|ects for which you want to add the constraint.
2. Choose a constraint from the Lditor > Add Constraint menu or an alignment type from the Lditor >
Alignment menu.
dit User Interfaces
Lay Out User |nterface Controls Using Content-Driven Pules
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
87
Any constraint that you have modified or added manually is considered a user constraint and is shown on the
canvas with a thicker line than used for the automatic constraints. |n the figure, the user constraint is the one
affecting the width, and the connections to the superview are automatic constraints.
Iigure 4-4 User constraint
Table 4-1 lists the types of Auto Layout constraints.
7abIe 4-1 Auto Layout constraints
Netes Iigure Censtraint
Select the ob|ect and choose
Lditor > Add Constraint >
width or Lditor > Constraint
> Height. Use the Attributes
inspector to specify the value
of the constraint. Por example,
"equal to 80 pixels, or "less
than or equal to 150 pixels.
The figure shows a constraint
that keeps the width of a
button greater than or equal
to some number.
Size (width or
height)
dit User Interfaces
Lay Out User |nterface Controls Using Content-Driven Pules
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
88
Netes Iigure Censtraint
Select all the ob|ects that you
want to include and then
choose either Lqual widths or
Lqual Heights from the Lditor
> Add Constraint menu. |f all
the ob|ects involved maintain
their intrinsic content size (see
"Allow Ob|ects to Maintain
Their |ntrinsic Content
Size" (page 90)), then the
width or height of the ob|ects
is that of the largest ob|ect in
the group. |f one of the
ob|ects has an explicit size,
then the other ob|ects assume
the same explicit size.
Lqual size
Select two ob|ects and then
choose either Horizontal
Spacing or vertical Spacing
from the Lditor > Add
Constraint menu. The figure
shows a button and a text
field with a set distance
between them.
Spacing
Select an ob|ect an choose
one of the superview
commands from the Lditor >
AddConstraint menu: Leading
Space to Superview, Trailing
Space to Superview, Top
Space to Superview, or
8ottom Space to Superview.
Use the Attributes inspector
to specify the space between
the ob|ect and its container.
The figure shows a constraint
holding the leading edge of a
button the standard aqua
space from the leading edge
of the container.
Superview-spacing
dit User Interfaces
Lay Out User |nterface Controls Using Content-Driven Pules
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
89
Netes Iigure Censtraint
Select all the ob|ects that you
want to include and then
choose an item from the
Lditor > Alignment menu.
Alignment constraints are
drawn as a straight line rather
than an | beam. Por example,
in the figure, the label and
text field are aligned along
their baselines.
Alignment
ou can edit constraints to specify such features as absolute or relative widths or heights.
7e edit a censtraint
1. Select the constraint.
2. |n the Attributes inspector, specify the type and value of the constraint, along with any other options.
Allow Ob|ects to Maintain Their |ntrinsic Content Size
|f there are no explicit constraints for width or height, an ob|ect assumes its |ntt|ns|c content s|ze , which is the
minimum size the ob|ect needs to be to hold its contents. Por buttons, that might be the title, an image, or
both. Por text fields, the contents consist of the string and the bezel, for a combo box, the string in the text
field and the disclosure button, and so forth.
Some ob|ects have an intrinsic content height, but not width. Others, such as buttons, have both an intrinsic
height and width. Some ob|ects, such as table views, have no intrinsic content size. when an ob|ect is set to
maintain its intrinsic content size, it resizes as needed to accommodate changes, such as differences in the
length of text strings due to localization.
As opposed to an ob|ect with an explicit size, an ob|ect that maintains its intrinsic content size (and has no
other size restraints) does not have the |-beam size constraint under it, as shown in Pigure 4-5. To specify
intrinsic content size, select the ob|ect and choose Size to Pit from the Lditor menu.
Iigure 4-5 8utton set to maintain its intrinsic content size
dit User Interfaces
Lay Out User |nterface Controls Using Content-Driven Pules
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
90
Override Automatic Constraints
ou can delete a user constraint, but not an automatic constraint. Pather than trying to delete automatic
constraints, create the constraints you want. Por example, suppose you place a button in the content view of
a window and |nterface 8uilder pins it to the upper leading edge of the window (Pigure 4-6).
Iigure 4-6 Automatic constraints
To pin the button to the trailing edge instead, add a constraint from the trailing edge of the button to the
trailing edge of the window (Pigure 4-7). |nterface 8uilder then automatically deletes the leading constraint
because the constraint you specified takes precedence.
Iigure 4-7 User-added trailing constraint
dit User Interfaces
Lay Out User |nterface Controls Using Content-Driven Pules
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
91
|f you want to pin the button to both sides, you can then add a second user constraint (Pigure 4-8).
Iigure 4-8 User-added leading constraint
Set Priorities to Pesolve Potential Conflicts
Occasionally, two constraints can come into conflict when a view is being resized. Por example, you might
have set your buttons not to get below a certain size, and also set a minimum width for the view containing
the buttons. ou can determine whether the minimum size for the window in this case is determined by the
view width constraint or the button width constraint by specifying a lower priority for one than the other. Por
example, if you set the priority for the button width constraint to 50 while the priority for the view width
constraint is 1000, Auto Layout will allowthe viewto be reduced to its minimumwidth even if it means reducing
the size of the buttons.
Design the User |nterface of our iOS App with Storyboards
|n Xcode 4.2, the |nterface 8uilder user interface for iOS applications is based on the storyboarding of view
controllers. Storyboarding enables you to use |nterface 8uilder to specify not only all the screens in your
application, but the transitions between them and the controls used to trigger the transitions. Thus you can
lay out every possible path through your application graphically, greatly reducing the amount of code you
need to write for a complex multiscreen application.
dit User Interfaces
Design the User |nterface of our iOS App with Storyboards
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
92
To create a pro|ect that uses view controllers, choose Pile > New > New Pro|ect and select the Use Storyboard
checkbox in the options dialog (Pigure 4-9).
Iigure 4-9 The Use Storyboard option
dit User Interfaces
Design the User |nterface of our iOS App with Storyboards
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
93
ou start with a view controller ob|ect that represents your first scene (the |n|t|ol v|ew conttollet ). To get view
controllers for your storyboard, select Ob|ects and Controllers from the Ob|ect library (Pigure 4-10) and drag
the view controllers you want onto the canvas. Lach view controller manages a single scene. On the iPhone,
each scene represents the contents of a single screen. Por iPad applications, a screen can be composed of the
contents of more than one scene.
Iigure 4-10 view controllers in the ob|ect library
To storyboard your application, you link each ob|ect that's in a view controller and that can cause a change in
the display, to another view controller that configures and implements the new scene (Pigure 4-11). ou link
the various view controllers in |nterface 8uilder by Control-dragging between controls and view controllers.
dit User Interfaces
Design the User |nterface of our iOS App with Storyboards
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
94
ou can drag from any control that has an output to the header of any other view controller. ou can add
controls and views to each view controller's view |ust as you would add ob|ects to a window or a view in the
nib file of an Xcode 3 or Xcode 4.0 application.
Iigure 4-11 Creating a storyboard
The arrows between viewcontrollers represent the segues fromone scene to another. To configure a seguefor
example, to specify the kind of transition to use between scenesclick the arrow and open the Attributes
inspector (Pigure 4-12). To define a custom transition, select Custom for the style of the segue and fill in the
dit User Interfaces
Design the User |nterface of our iOS App with Storyboards
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
95
name of your custom segue class. Standard segue classes are in U|Kit (see ull|t ltomewotl keletence ). Por
information about implementing the methods in the bTv1ewCoh1Jo11eJ class, see ulv|ewConttollet Closs
keletence .
Iigure 4-12 Attributes inspector for a segue
dit User Interfaces
Design the User |nterface of our iOS App with Storyboards
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
96
The result is a storyboard that graphically represents every screen of your application and the flow of control
among the screens. Double-click the canvas to zoom out to see the entire storyboard (Pigure 4-13).
Iigure 4-13 Storyboard for an iOS Application
Create User |nterface Classes
|f you need a customviewob|ect or a viewcontroller, you create the newclasses in the pro|ect navigator. Once
you've created the interface and implementation files, you can connect user interface ob|ects in an |nterface
8uilder nib file or storyboard directly to your code files or you can add connections in the nib file or storyboard
between |nterface 8uilder ob|ects and existing outlets and actions in the nib file or storyboard .
when you create a newMac OS X application or iOS view-based pro|ect, Xcode includes a nib file for your main
view and a view controller class. when you create a new iOS storyboard-based pro|ect, Xcode includes a
storyboard and a view controller class. The view controller is represented in the nib file as the Pile's Owner
dit User Interfaces
Create User |nterface Classes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
97
ob|ect. when you need a new nib file for a pro|ect, you should create the interface and implementation files
for the controller first. |n many cases, Xcode creates a nib file as well. As nib files usually have controllers already
assigned to them, it is rarely necessary to add a separate view controller to a nib file.
Add a New Nib Pile
when you need a new nib file, first add interface and implementation files for the controller to the pro|ect. |n
some cases, you automatically get a new nib file as well. |f not, you can then add a nib file and link it to the
controller.
7e add a new nib fiIe te a preject
1. Choose Pile > New > New Pile and select the template type for your new controller files.
2. Click Next and specify the name and parent class of the new controller.
dit User Interfaces
Create User |nterface Classes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
98
|n the figure, for example, the new class will be a subclass of NSW1hdowCoh1Jo11eJ named
^yW1hdowCoh1Jo11eJ.
3. Click Next, specify the location for the new files, and click Create. Xcode creates a header file and an
implementation file and adds them to your pro|ect.
|n some cases, such as if you add a controller that's a subclass of NSv1ewCoh1Jo11eJ, you automatically
get a nib file as well. |f so, skip to step 5.
4. Add a nib file by choosing Pile > New > New Pile and selecting a User |nterface template in the New
Pile dialog.
dit User Interfaces
Create User |nterface Classes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
99
The following figure shows a Mac OS X user interface file of type window being selected in the New
Pile dialog.
7ip: 8e sure you select the appropriate file type for the correct platform. Por example, there
are two nib templates named Application: one for iOS, and one for Mac OS X.
dit User Interfaces
Create User |nterface Classes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
100
5. Open the new nib file by selecting it in the pro|ect navigator so that it appears in the |nterface 8uilder
editor.
6. Select the Pile's Owner ob|ect in the |nterface 8uilder dock and choose your controller in the class field
under Custom Class in the |dentity inspector.
|f your nib file was added automatically by Xcode, it will probably already be set to the appropriate
controller, but you should check to be certain.
7ip: |nstead of using the New Pile dialog, you can drag controller and interface files from the Pile Template
library into the pro|ect navigator. when dragging into the pro|ect navigator, be sure the group into which
you want to drop the file is highlighted before you drop, you won't get the results you want if you accidentally
drop the file inside another file.
To see the outlets and actions provided by the parent class of the Pile's Owner, click the Pile's Owner ob|ect
in the dock and open the Connections inspector. To add new actions or outlets to the nib file's controller, see
"Make Connections Directly 8etween |8 Ob|ects and our Code Piles" (page 107).
dit User Interfaces
Create User |nterface Classes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
101
Add a Custom view
A custom view is a new subclass of one of the standard views used by |nterface 8uilder, such as NSv1ew or
NSBu11oh. To add a custom view, first create the view's class in the pro|ect navigator, then add the view to
your nib.
7e add a custem view te a nib fiIe
1. Create header and implementation files for the view by choosing Pile > New > New Pile and selecting
the Ob|ective-C class template. 8e sure to choose the appropriate parent class in the "Subclass of
pop-up menu.
2. Drag a custom view ob|ect from the library into the nib file.
3. Select the custom view and assign the correct class to it in the class field under Custom Class in the
|dentity inspector (see step 3 of "To add a new nib file to a pro|ect" (page 98)).
|f your custom class doesn't appear in the pop-up menu, you can type it in.
dit User Interfaces
Create User |nterface Classes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
102
Add a New Controller
Lvery nib file is created with a Pile's Owner ob|ect, which you link to the controller for the file. |n the rare event
that you need to add another controller to a nib file (to control a subview, for example), you need to create
source files for the controller and add a controller ob|ect to the nib file so that you can make connections to
the controller.
7e add a centreIIer te a nib fiIe
1. Create header and implementation files for the controller by choosing Pile > New > New Pile and
choosing the Ob|ective-C class template with NS0bec1 in the "Subclass of pop-up menu.
2. Drag the Ob|ect ob|ect from the Ob|ect library in the utilities pane into the dock of your |nterface
8uilder nib file.
7ip: Type hsobec1 into the search field to find the ob|ect quickly.
dit User Interfaces
Create User |nterface Classes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
103
3. Use the class field under Custom Class in the |dentity inspector to assign the class of your controller
to the ob|ect.
4. Use the Label field in the |dentity inspector to assign a display name to your controller ob|ect.
To see the outlets and actions provided by the controller, click the controller ob|ect in the dock and open the
Connections inspector. To add newactions or outlets to the controller, see "Make Connections Directly 8etween
|8 Ob|ects and our Code Piles" (page 107).
Simultaneously Design and |mplement User |nterface Ob|ects Using
Multiple Lditors
when you use custom subclasses in your interface, or add outlets and actions to a controller, you can use an
assistant editor pane to work on your interface code at the same time as your U| design.
7e use Assistant witb Interface 8uiIder
1. Select your nib file in the pro|ect navigator to open |nterface 8uilder.
2. Select the interface ob|ect for which you want to add outlets and actions.
3. Click the Assistant button to open the assistant editor pane.
dit User Interfaces
Simultaneously Design and |mplement User |nterface Ob|ects Using Multiple Lditors
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
104
4. |f the assistant editor does not automatically display the header file you want, use the assistant editor
pane |ump bar to select the source file containing the controller code for the ob|ect.
7ip: Choose view > Assistant Layout to select the orientation of the split between the source
and assistant editors.
ou can write code for the window controller at the same time you are designing your window, and you can
make connections directly between |nterface 8uilder ob|ects and lines in your code. Pigure 4-14 shows a
window ob|ect selected in the |nterface 8uilder pane with the assistant editor pane displaying the file
SKTW1hdowCoh1Jo11eJ.m. The oval containing the numerals 4/5 at the right end of the assistant editor |ump
dit User Interfaces
Simultaneously Design and |mplement User |nterface Ob|ects Using Multiple Lditors
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
105
bar indicates that the fourth of five counterpart files is being displayed (in this case the others are
SKTW1hdowCoh1Jo11eJ.h, SKTCJaph1cv1ew.h, SKTCJaph1cv1ew.m, and NSW1hdow.h). Click the right
or left arrows to display the others in turn.
Iigure 4-14 |nterface 8uilder and Assistant
Manage Connections 8etween User |nterface Ob|ects
The ob|ects in your user interface must communicate with each other and with your source code if your program
is to interact with the user. To specify which messages are sent and received, you use |nterface 8uilder to create
connections. There are four fundamental types of connections you can create:
!
Outlet connections
!
Action connections (Mac OS X only)
dit User Interfaces
Manage Connections 8etween User |nterface Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
106
!
Lvent connections (iOS only)
!
8indings (Mac OS X only)
Make Connections Directly 8etween |8 Ob|ects and our Code Piles
ou can make a connection directly froman |nterface 8uilder ob|ect to the appropriate header or implementation
file, and, if needed, Xcode inserts code directly into your header and implementation files.
Pigure 4-15 shows a connection being made to an existing TBAc11oh statement.
Iigure 4-15 Making a connection to source code from |nterface 8uilder
Connect an ob|ect directly to the declaration of a new outlet in a source file.
7e create and cennect a new eutIet . . .
1. with a nib file open, click the Assistant button.
2. |n the |ump bar, select the header file in which you want to declare a new outlet.
3. Control-drag from a nib ob|ect to the location in the header file for the new outlet.
4. |n the dialog, choose Outlet from the Connection menu.
dit User Interfaces
Manage Connections 8etween User |nterface Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
107
5. Type the name of the new outlet and click Connect.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
As you Control-drag from an ob|ect to your source code, |nterface 8uilder indicates where a new outlet is
valid. After you enter the name of the outlet, |nterface 8uilder declares the outlet for you and connects the
ob|ect to it. ou can choose to make the outlet an instance variable or a property.
ou may need to add source code that uses the outlet. ou can Option-click the name of your controller's
implementation file in the source editor's |ump bar to open the implementation file alongside the header
file.
The video shows connecting an NS^a1J1x ob|ect to a property outlet in a window controller class.
AIternative: Declare the outlet in your source code manually, then connect an ob|ect directly
to the outlet declaration.
Connect an ob|ect to the declaration of a new action method in a header file.
7e create and cennect a new actien . . .
1. Choose view > Assistant Lditor > Open Assistant Lditor.
2. |n the primary editor, open the user interface document that contains the ob|ect that invokes the new
action.
3. |n an assistant editor, open the header file to which to add the action-method declaration.
4. Control-drag from the ob|ect to the header file.
5. Choose Action from the Connection menu.
6. Lnter the name of the action method, and click Connect.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
dit User Interfaces
Manage Connections 8etween User |nterface Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
108
As you Control-drag from an ob|ect to your source code, Xcode indicates where a new action is valid. After
you enter the name of the action, Xcode declares the action for you and connects the ob|ect to it.
Xcode also inserts a skeletal definition for the new action in the implementation file. ou need to add the
source code that implements the action. ou can Option-click the name of the implementation file in the
source editor's |ump bar to open the implementation file alongside the header file.
The video shows connecting a button matrix to a new action in a window controller class.
|f you make the connection to a header file, Xcode also inserts code in the corresponding implementation file
as appropriate. Por example, if you use |nterface 8uilder to place a new action called 1oadCompos111oh in a
header file, Xcode inserts the line
- {TBAc11oh)1oadCompos111oh:{1d)sehdeJ,
in the header file and, in the corresponding implementation file, Xcode inserts
- {TBAc11oh)1oadCompos111oh:{1d)sehdeJ {
]
oucanthenput your implementationcode for the 1oadCompos111ohmethoddirectly intothe implementation
file.
dit User Interfaces
Manage Connections 8etween User |nterface Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
109
Nete: 8ecause Xcode 4 parses both your header files and implementation files for indexing, you
can define actions and outlets in implementation (.m) files without needing to place them in the
header file and you can make connections directly from the nib file to the implementation file.
Therefore, you do not need to expose parts of your interface or actions to clients who might be using
your classes.
Note that, because the Control-click key combination is used by |nterface 8uilder to make connections, you
must Control-click on the canvasnot on any ob|ect in the user interfaceto get the shortcut menu with the
list of help articles for |nterface 8uilder (Pigure 4-16).
Iigure 4-16 Help articles in |nterface 8uilder
Add Outlets and Actions to Classes Programmatically
The easiest way to add an outlet or action to your controller class is by dragging from an |nterface 8uilder
ob|ect, as described in the preceding section. However, in some cases you might want to define certain outlets
or actions in your code before configuring connections in |nterface 8uilder. To do so, you use the TB0u11e1,
TB0u11e1Cohhec11oh, and TBAc11oh keywords in your code. 8ecause Xcode 4 indexes both header and
implementation files, you can add outlets and actions to the implementation file only so that you do not expose
your connections to clients who use your public header files.
dit User Interfaces
Manage Connections 8etween User |nterface Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
110
Use the |nspector or the Connections Panel to Make Connections
ou can manage outlet, action, and event connections by using the inspector or the connections panel. These
two tools provide the same basic behavior but do so in slightly different ways. The Connections inspector
displays the connections associated with the currently selected ob|ect. Changing the selection changes the
contents of the inspector. The connections panel is an on-demand window that you open by Control-clicking
the ob|ect. The connections panel displays the connections for the same ob|ect until the panel is dismissed.
ou can open multiple connections panels at the same time.
ou can use the techniques described in this section to make connections that are already defined in the source
code or systemframeworks. To define newoutlets, actions, or events, see "Make Connections Directly 8etween
|8 Ob|ects and our Code Piles" (page 107).
7e make a quick cennectien
1. Control-drag from the source ob|ect to the target ob|ect. |f a connection is possible with the target
ob|ect, the target ob|ect is highlighted.
2. when you complete the drag, |nterface 8uilder displays a prospective list of actions and outlets.
3. Select an outlet (of the source ob|ect) or an action or event (of the target ob|ect) to create the connection.
when you use the Control-drag gesture to create a connection for an action or event, the final part of the
task involves picking the action or event from a list. Outlet connections display a similar list. |f there are
previous connections that have the same name, the menu items to pick those names are flagged. |f a
connection identical to the one being made already exists, the menu item is flagged with a dot. |f a
connection exists with that name, but to a different ob|ect, it is flagged with a dash.
7ip: Por action connections in Mac OS X, this technique is equivalent to opening the connections panel and
configuring the source ob|ect's sent actions connection. 8ecause a source ob|ect in Mac OS X can send its
action message to only one target ob|ect, you should use this technique only once to configure a given source
ob|ect's action connection. Pepeating the process for the same source ob|ect would break the old connection
before establishing the newone. ou can use this technique, however, to configure each of the source ob|ect's
outlets.
7e make a cennectien using tbe cennectiens paneI
1. Control-click an ob|ect and release the mouse button to display the panel.
2. Drag fromthe circle to the right of the action, outlet, or event you want to connect to the target ob|ect.
|f the target of a connection is not visible, holding the pointer over its parent ob|ect causes the parent
to open and reveal its children.
|f a connection is possible with the target ob|ect, the target ob|ect is highlighted.
dit User Interfaces
Manage Connections 8etween User |nterface Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
111
3. |f you are using the connections panel to configure the sent action or referencing outlet for the ob|ect,
when you complete the drag, |nterface 8uilder displays a list of the target ob|ect's action methods or
outlets. Select an action method or outlet from the list to finish the connection.
4. |f you want to select other ob|ects in your nib file but do not want the connections panel to disappear,
drag the panel to a new location.
ou do not have to drag the window far, even dragging it a single pixel is sufficient. Note that if you
do this, you must dismiss the window yourself by clicking its close box when you are done.
After you establish a connection, the connections panel fills the circle next to that action or outlet and
displays information about the connection. Lach connection also includes a close box icon that you can
use to break the connection. |f a received action has multiple source ob|ects associated with it, the panel
displays a disclosure triangle, which you can use to reveal the individual connections. |f you select a
connection, |nterface 8uilder displays a path control at the bottom of the panel and a "take me there"
button for the selected connection.
The connections panel remains visible as long as you use it. |f you click outside the panel (by selecting a different
ob|ect in your window, for example) |nterface 8uilder dismisses the panel automatically to get it out of your
way. ou can also dismiss the panel explicitly by clicking its close box.
ou can start an action or event connection at the source ob|ect to connect from the sent action selector (for
Mac OS X applications) or to connect from an event (for iOS applications). ou can start a connection at the
target ob|ect to connect one of its action methods to a source ob|ect.
when connecting from target to source, you can connect each action method multiple times. After you make
the first connection, the circle next to the action method is filled to show that there is an associated source
ob|ect. To connect an additional source ob|ect, drag fromthe circle to the target ob|ect. Performing this action
does not remove the original connection.
Like action connections, you can create outlet connections starting at either the source or target ob|ect. |n
Mac OS X and in iOS 3.3 and earlier, only one ob|ect at a time may be connected to a given outlet. |n iOS 3.4
and later, multiple ob|ects can be connected to a given outlet.
ou can also use the Connections inspector to make and viewconnections. The Connections inspector provides
a summary of the outlets and actions (or events) of the selected ob|ect. ou can use the inspector to view the
status of connections, to create new connections, and to break existing connections.
7e make a cennectien using tbe inspecter
1. Open the Connections inspector and select an ob|ect.
dit User Interfaces
Manage Connections 8etween User |nterface Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
112
2. Drag from the circle next to the entry you want to connect to the target ob|ect for the connection. (|f
the target of a connection is not visible, holding the pointer over its parent ob|ect causes the parent
to open and reveal its children.) |f a connection is possible with the target ob|ect, the target ob|ect is
highlighted when you hold the pointer over it.
3. |f you are using the Connections inspector to configure the sent action or referencing outlet for the
ob|ect, when you complete the drag, |nterface 8uilder displays a list of the target ob|ect's action methods
or outlets. Select an action method or outlet from the list to finish the connection.
After you establish a connection, the Connections inspector fills the circle next to that entry and displays
information about the connection. Lach connection also includes a close box icon that you can use to break
the connection. |f a received action has multiple source ob|ects associated with it, the panel displays a
disclosure triangle, which you can use to reveal the individual connections.
8reak and Peconfigure Connections
At times you may need to break an existing connection and replace it with a new one. ou can use either the
Connections inspector or the connections panel to do so.
Change an ob|ect's connections to other ob|ects in a nib file using the connections panel. After making a
connection directly to your source code, you may need to change or remove the connection. The connections
window shows you all the connections to and from an ob|ect, and makes it possible to change or remove
them.
7e cbange a cennectien . . .
1. with a nib file open, Control-click an ob|ect to open the connections window.
2. Click the X to the left of the connection name to remove a connection.
3. Drag from the connection well directly to your source code to add a connection.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
The specific connections listed in the connections window depend on the ob|ect you select. Types of
connections include Cocoa Touch events, actions, outlets, outlet collections, and bindings. |f a connection
exists, the circle on the right (called a connect|on well ) is filled in and the name of the connected ob|ect is
shown.
dit User Interfaces
Manage Connections 8etween User |nterface Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
113
Por actions, Cocoa Touch events, and referencing outlets, you can create a connection by dragging from
the connections window directly to your source code. |f you're changing a connection, it's not necessary
to remove the old connection in order to change it.
The video shows changing an action connection.
AIternative: ou can also change an ob|ect's connections using the Connections inspector.
Connect Menu |tems to our Code or our Pirst Pesponder
There are two common techniques for handling menu commands in a Mac OS X application:
!
Connect the corresponding menu item to a first responder method.
!
Connect the menu itemto a method of your customapplication ob|ect or your application delegate ob|ect.
Of these two techniques, the first is somewhat more common given that many menu commands act on the
current document or its contents, which are part of the responder chain. The second technique is used primarily
to handle commands that are global to the application, such as displaying preferences or creating a new
document. |t is possible for a custom application ob|ect or its delegate to dispatch events to documents, but
doing so is generally more cumbersome and prone to errors.
Nete: |n addition to implementing action methods to respond to your menu commands, also
remember to implement the methods of the NS^ehuva11da11oh protocol to enable the menu
items for those commands.
Configure Connections 8etween Model and view Ob|ects
Cocoa bindings are a controller-layer mechanism used to synchronize the view and model layers of your Mac
OS X application. 8indings establish a mediated connection (through a controller ob|ect) between a view and
a piece of data, binding them in such a way that a change in one is reflected in the other.
One of the advantages of using bindings over traditional glue code is that you can use |nterface 8uilder to
configure them. Ob|ects with bindable properties can expose those properties in |nterface 8uilder. ou can
then configure that binding directly using the 8indings inspector. The configured bindings are saved in the
nib file and re-created at runtime like other types of connections.
ou configure bindings in |nterface 8uilder by starting at the ob|ect that exposes a bindable propertytypically,
a view or controller ob|ect. ou then use the 8indings inspector to specify the target of the binding and the
binding options. ou must configure each binding separately and each binding can be attached to a different
dit User Interfaces
Configure Connections 8etween Model and view Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
114
target ob|ect. The target of a binding is always one of the recognized controller ob|ects in your nib file, which
typically includes the Pile's Owner, the application, the shared user defaults controller, and any customcontroller
ob|ects (especially NSCoh1Jo11eJ ob|ects) you add to the nib file.
Por more information about how Cocoa bindings work, see Cocoo 8|nJ|ns ltotomm|n !o|cs .
Nete: Cocoa bindings are not available in iOS.
Create and Configure a 8inding with the 8indings |nspector
|n |nterface 8uilder, you typically bind views and controller ob|ects in your nib file to the data in your custom
controller ob|ects.
7e create a binding
1. Create the views needed to display your data.
2. Create any intermediate controller ob|ects needed to manage your data. (Typical controller ob|ects
include instances of your customNS0ocumeh1 or NSW1hdowCoh1Jo11eJ subclasses, NSCoh1Jo11eJ
subclasses, or custom NS0bec1 subclasses that you create to manage your data structures.)
3. Use the 8indings inspector to configure each binding.
dit User Interfaces
Configure Connections 8etween Model and view Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
115
Although each binding displays several configuration options, the most important part of a binding is the
target of the binding. ou must configure, at a minimum, the following fields for any given binding:
!
8ind to
!
Model Key Path
The 8ind te field specifies the controller ob|ect to use as the starting point for accessing the target data.
The MedeI key Patb field contains a string representing the key path for the data. Key path strings are of the
form <pJopeJ1y_hame>[.<pJopeJ1y_hame>]+. The first property name in this string is a property on the
controller ob|ect specified by the 8ind to field. Lach subsequent property name corresponds to a property of
the ob|ect returned by the previous property name. Say, for example, that you have a custom controller ob|ect
and the key path string "peJsoh.addJess.s1Jee1". The peJsoh property returns the person ob|ect of the
bound controller. The addJess property returns the address of the corresponding person ob|ect. And the
s1Jee1 property returns the data value stored in the address ob|ect.
Create a 8inding by Dragging Directly to our Header Pile
As with outlets and actions, you can drag directly from an ob|ect in your nib file to code in your header file to
create a binding.
8ind an ob|ect directly to a declaration in a header file.
7e create a binding by dragging . . .
1. with a nib file open, display the Assistant editor.
2. |n the |ump bar of the Assistant editor, choose the header file of the ob|ect to which you will make the
binding.
3. Control-drag from a nib ob|ect to the symbol in the header file for the new binding.
4. |n the dialog, configure the binding and click Connect.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
dit User Interfaces
Configure Connections 8etween Model and view Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
116
As you Control-drag from an ob|ect to your source code, |nterface 8uilder indicates where a new binding
is valid. After you've made the connection, Xcode displays a dialog you use to configure the binding. ou
can use the dialog to configure all aspects of the binding.
|nterface 8uilder uses the Xcode index to determine which key paths are valid, and can also discover what
controller it should connect throughyou can therefore connect from a user interface element such as a
table column to a property in a model class header.
Nete: |f the dock on the left of your |nterface 8uilder editor does not look like the one in the
video, click the button at the bottom of the dock ( ) to toggle from outline view to icon view.
Key Paths Are Dependent on our Data Model
The best way to understand how to bind key paths in |nterface 8uilder is to go through some examples. The
following sections show how to bind a text field to an NSNumbeJ ob|ect to display the number value in that
text field. |n each successive example, the data model used to access the number value gets progressively
more complex, and so the bindings must be ad|usted in accordance with the increased complexity.
Por bindings examples, see Cocoo 8|nJ|ns ltotomm|n !o|cs .
8ind a Document Ob|ect Directly to a value
The simplest key path occurs when you bind your |nterface 8uilder ob|ect directly to a data value in your code.
7e set up a simpIe ebject-data reIatiensbip
1. Set the target ob|ect to the document's Pile's Owner.
The document ob|ect must be KvC compliant.
2. Set the model key path to the name of the instance variable.
8ind a Document Ob|ect to a Data Ob|ect Through an Ob|ect Controller
Prequently, the Pile's Owner isn't the main data-containing ob|ect. |nstead, you typically have other data ob|ects
(often held in a collection), referenced by the Pile's Owner. |n this case, you should add an ob|ect controller
(an NS0bec1Coh1Jo11eJ ob|ect) and bind the user interface ob|ect (the view ob|ect) to the data ob|ect
through the controller ob|ect and the Pile's Owner. The controller ob|ect acts somewhat like a buffer layer
between your view and data ob|ect and the controller ob|ect acts as a placeholder for the document's current
Eh1Jy ob|ect, providing a valid binding target even if the document's eh1Jy property becomes h11.
dit User Interfaces
Configure Connections 8etween Model and view Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
117
7e bind te a data ebject tbreugb an ebject centreIIer
1. Set the target ob|ect to the NS0bec1Coh1Jo11eJ ob|ect.
The ob|ect controller, document ob|ect, and data ob|ect must all be KvC compliant.
2. Choose either se1ec11oh or se1ec1ed0bec1s in the Controller Key pop-up menu.
3. Add the target property in the Model Key Path field.
Mac OS X combines the strings in the Controller Key and Model Key Path fields to get the final key
path.
8ind to a Collection of Ob|ects Through an Ob|ect Controller
Using controller ob|ects, it is as simple to bind to a collection of ob|ects as it is to bind to a single ob|ect. |n
fact, the bindings themselves are almost identical. |nstead of binding to a single ob|ect, you bind the view to
a collection of ob|ects through an NSAJJayCoh1Jo11eJ ob|ect. The array controller manages both the
collection of ob|ects and the list of indexes corresponding to the selected ob|ects and uses that information
to provide an appropriate value to the text field.
7e bind te a ceIIectien ef ebjects
1. 8ind the text field to an NSAJJayCoh1Jo11eJ ob|ect's se1ec11oh property, which represents the
currently selected Eh1Jy ob|ect.
2. Specify the quah111y string for the key path.
Configure the 8inding Attributes to Customize the 8inding
Although the 8indings inspector may seem complex at first, for many bindings, you need to configure only a
few options initially. ou may not need to configure every option every time (except for the 8ind to and Model
Key Path fields). During your initial design phase, you can probably leave most of the options configured with
their default values. As you improve your design, you can customize the options more until you have the
behavior you want.
Por a complete list of bindings available for a given view or controller ob|ect, see Cocoo 8|nJ|ns keletence .
8ind to Ob|ects in a Custom Tree Data Structure
|f your programcontains a customtree data structure, you can use an NSTJeeCoh1Jo11eJ ob|ect to coordinate
bindings to the ob|ects in that data structure. Tree controllers are often used to bind data ob|ects to an
NSBJowseJ or NS0u111hev1ew ob|ect in order to display hierarchical sets of data to the user.
dit User Interfaces
Configure Connections 8etween Model and view Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
118
7e cenfigure a tree centreIIer ebject
1. Add the tree controller ob|ect to your document and select it.
2. Open the Attributes inspector.
3. Pill in the Ob|ect Controller section.
!
|n the Class Name field, specify the class name of the ob|ects in the tree.
!
Optionally, specify any custom keys of the tree ob|ects that you want to expose in the Model Key
Path field of the bindings inspector.
4. Pill in the Tree Controller section.
!
|n the Children field, specify the key path for the property that identifies the child nodes of a given
tree ob|ect.
!
|n the Count field, specify the key path for the property that indicates how many children a given
tree ob|ect has. (This key path is optional.)
!
|n the Leaf field, specify the key path for the property that identifies whether the current tree
ob|ect is a leaf node. (This key path is optional but recommended because it can improve the tree
controller's performance as it navigates your tree at runtime.)
Por more information on using tree controllers, see Cocoo 8|nJ|ns ltotomm|n !o|cs .
8ind to our Application Preferences
An NSbseJ0e1au11sCoh1Jo11eJ ob|ect is most often used when implementing a preferences window or
in any situation where you want to bind a view to values in the defaults database. Although you can add a
new NSbseJ0e1au11sCoh1Jo11eJ ob|ects to your nib file, you generally do not need to do so. |nterface
8uilder provides a shared user defaults controller ob|ect that you can use to bind to your application's
preferences.
7e use tbe sbared defauIts centreIIer te impIement yeur appIicatien's preferences windew
1. Select the control you want to bind to a preference.
2. Open the 8indings inspector.
3. |n the appropriate binding for your control, set the 8ind to field to Shared User Defaults Controller.
4. |n the Model Key Path field, enter the key name of the preference you want to associate with the
control.
dit User Interfaces
Configure Connections 8etween Model and view Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
119
7ip: 8y default, the shared user defaults controller sets the value in the Controller Key field to "values. 8ecause
individual preference values are accessed through this property on the user defaults controller, you should
leave this field configured as is.
Por more information on configuring user defaults bindings, see "User Defaults and8indings" in Cocoo 8|nJ|ns
ltotomm|n !o|cs .
dit User Interfaces
Configure Connections 8etween Model and view Ob|ects
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
120
ou write and edit code with the Xcode source editor, which has many professional-level features, such as
automatic formatting, code completion and correction, and online documentation. ou can discover most of
these features by looking in the Ldit and Lditor menus as well as Control-clicking in the editor to see the
contextual menu. This chapter briefly reviews the features you are likely to use most often and describes some
features that you might not discover easily by yourself.
|n addition to writing and editing code in the source editor, you can set breakpoints, viewthe values of variables,
step through running code, and review issues found during builds or code analysis. These features are part of
the debugging and build-run workflows, and so are discussed in other chapters (see "Debug our App" (page
180) and "Configure our Pro|ect" (page 66)).
Customize the Source Lditor with Xcode Preferences
Here are some of the ways you can customize both the appearance and function of the source editor in Xcode
preferences by using the Ponts & Colors, Text Lditing, and Key 8indings panes.
Modify Syntax-Aware Ponts and Text Colors
Xcode parses code based on the language (as determined fromthe filename extension) and assigns a syntactic
label to each token or string: comment, keyword, class name defined in the pro|ect, other class name, and so
forth. 8y default, Xcode assigns a color and font to each syntactic type to make it easier for you to read the
code. Xcode Ponts & Colors preferences allows you to select among several font and color themes, for example,
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
121
Ldit Source Code
the Presentation theme increases the font sizes so that the text is easier to read when pro|ected on a screen.
ou can also create your own custom font and color theme. Por example, in Pigure 5-1, symbols defined in the
pro|ect are given a distinct color to make them easier to pick out.
Iigure 5-1 Ponts & Colors preferences
Customize the appearance of source code and console text by changing their colors and fonts in Ponts &amp,
Colors preferences. Por example, you could display your code comments in purple in the source editor. Por
the console, you could set your debugger input and your debugger output to a 14-point font.
7e set fent and ceIer preferences . . .
1. Choose Xcode > Preferences and click Ponts & Colors.
2. Click either Source Lditor or Console near the top of the preferences window.
3. Select a theme.
4. Select a syntax category.
5. To change the font, click the Ponts window button, and make your selections in the Ponts window.
dit Seurce Cede
Customize the Source Lditor with Xcode Preferences
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
122
6. To change the text color, click the font color well, and choose a new color in the Colors window.
7. To change the color of other items in the source editor or console, click a color well at the bottom of
the pane, and choose a new color.
The source editor's Comments category for the Default theme is selected in the screenshot. Atheme includes
preset colors and fonts for all the syntax categories. Xcode includes a set of standard themes, such as Default,
that you can modify or delete. ou can restore any of the standard themes by selecting from a set of
templates that are displayed when you click the Add (+) button at the bottom of the theme list.
Por the source editor and the console, you can also customize colors for the:
!
8ackground
!
Selection
!
Cursor
!
|nstruction pointer (for the console)
7ip: ou can change the font or font size for all the syntax categories in a theme. Select a category,
press Command-A to select all categories, and modify the settings for the font or font size.
Customize the keyboard shortcut for a command by editing its key sequence in the Key 8indings preferences
pane.
7e custemize keybeard sbertcuts . . .
1. |n the Key 8indings preferences pane, choose a command set to edit.
2. Locate the command for which you want to change the shortcut.
dit Seurce Cede
Customize the Source Lditor with Xcode Preferences
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
123
3. Double-click a key sequence to select it.
4. Type a new key sequence to replace the selected one.
5. Click elsewhere in the detail area to apply your change.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
To edit the key binding for a command, double-click its key field, and then:
!
To change a selected sequence, type a new one to replace it.
!
To remove a selected sequence, click the Pemove () button. (Do not press the keyboard Delete key,
that |ust adds Delete to the key sequence.)
!
To enter a sequence in an empty key field, type the sequence.
!
To add a sequence to an existing one, click the Add (+) button and type the new sequence. This only
works for text commands, you cannot assign more than one sequence to a menu command.
Impertant: when you have made your changes, be sure to click outside the key field to close it. Pressing
any key while the field is open changes the key sequence.
Specify a key sequence by typing it |ust as you would type it to use it, for example, to specify ^A, hold down
the Control key and type the letter a.
A specific key sequence can be bound to only one command, if you enter one that is already assigned to
another command, Xcode removes it from that other command.
The video shows adding the key sequence Control-Option-Pight Arrowas a shortcut for the Move Lxpression
Pight command.
Por detailed information about key bindings, see "Text System Defaults and Key 8indings in Cocoo
lvent-lonJl|n Cu|Je .
dit Seurce Cede
Customize the Source Lditor with Xcode Preferences
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
124
Set our Text-Lditing and Automatic |ndentation Preferences
ou can set several preferences that control the appearance and behavior of the source editorincluding
whether line numbers are displayed, how delimiter balancing and the code focus ribbon work, and some
aspects of code completionin the Lditing pane of Text Lditing preferences.. ou can control many of the
automatic-indenting features of the editor in the |ndentation pane of Text Lditing preferences. Control-click
in either pane to see a help article that describes the use of the fields.
Lnter Code uickly and Accurately with the Help of the Source Lditor
The source editor includes several features that help you enter code and avoid mistakes:
!
Code completion
!
uick Help
!
Automatic delimiter balancing
!
Automatic indenting
!
Syntax formatting
!
Pix-it
Speed Up Typing with Code Completion
when you begin typing the name of a symbol that Xcode has indexed, it offers an inline suggestion for
completing the symbol name plus a list of possibilities (Pigure 5-2). Click an item in the suggestion list or use
the Up Arrow and Down Arrow keys to select one. As you do so, the inline suggestion changes as well.
dit Seurce Cede
Lnter Code uickly and Accurately with the Help of the Source Lditor
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
125
Purthermore, as you can see in the figure, if you open the Symbol inspector in the utility pane, you can read
documentation about each selection. ou can turn off automatic code completion in the Text Lditing pane of
Xcode preferences, but you can always invoke code completion by pressing Control-Space bar or Lsc.
Iigure 5-2 Code completion
Pinish entering a symbol by accepting an Xcode suggestion for completion. The proposed symbol is based on
the text you have typed so far and the surrounding context. Continue typing to refine the list of choices.
7e enter text witb cede cempIetien . . .
1. 8egin typing the name of a symbol.
2. Click an item in the suggestion list.
3. Press Peturn to accept the suggestion.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
|f all of the possible completions have a common prefix, the prefix is indicated with a dotted underline.
Press the Tab key to accept only the prefix, or press Peturn to accept the entire suggestion.
dit Seurce Cede
Lnter Code uickly and Accurately with the Help of the Source Lditor
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
126
Press Control-Space bar to toggle the completion suggestion on or off. That is, if the inline suggestion and
list are being displayed, pressing Control-Space bar cancels the code completion operation. (Pressing the
Lsc key or clicking elsewhere in the text also cancels the operation.) |f there is no suggestion displayed,
place the insertion point at the endof a partially-typedsymbol andpress Control-Space bar to get completion
suggestions.
To turn off the code completion feature, choose Xcode > Preferences and click Text Lditing. |n the Lditing
pane, deselect the option "Suggest completions while typing. ou can always invoke code completion by
pressing Control-Space bar.
Auick Help pop-up windowis available fromcode completion. Hold the pointer over the code completion
option you're interested in until a question mark icon appears. Click the question mark to open uick Help.
As before, press the Tab key to accept the prefix or Peturn to accept the entire suggestion. Click the Done
button in the uick Help window to close the window.
when a method or function contains parameters or arguments, code completion includes a placeholder
for each. Choose the 1ump to Next Placeholder (Control-/) and 1ump to Previous Placeholder (Control-Shift-!)
items in the Navigate menu to move from one placeholder to another.
dit Seurce Cede
Lnter Code uickly and Accurately with the Help of the Source Lditor
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
127
Nete: The code completion feature is not fully functional until Xcode finishes indexing your
pro|ect.
Code completion inline quick help is shown in Pigure 5-3. Code completion placeholders for parameters are
shown in Pigure 5-4.
Iigure 5-3 uick Help for code completion
Iigure 5-4 Placeholders in code completion text
8alances Delimiters Automatically
when you create a new file or edit an existing one, Xcode determines the source language from the filename
extension and attempts to determine the syntax of the text based on the source type. Por example, a file with
a .h or .m extension is assumed to be a variety of C and formatted accordingly. |n that case, the editor indents
the text according to the rules you set in Text Lditing preferences and uses fonts and colors for the various
syntax elements (variables, constants, comments, and so forth) according to the settings in the Ponts & Colors
pane of Xcode preferences.
when you're writing code, type an opening brace ([), and continue typing, Xcode automatically adds a closing
brace (}) unless you've deactivated this feature in Text Lditing preferences. There are several other features
that help you to balance delimiters, including double-clicking a delimiter to select the entire expression.
7e get assistance in baIancing deIimiters
Do one of the following:
dit Seurce Cede
Lnter Code uickly and Accurately with the Help of the Source Lditor
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
128
!
Type an opening brace.
Xcode automatically inserts a closing brace after you enter a line break. (|f you don't want closing braces
automatically inserted, choose Xcode > Preferences, click Text Lditing, and deselect "Automatically
insert closing '}'.)
!
Use the Pight Arrow key to move the insertion point past a closing delimiter.
Xcode briefly highlights its counterpart.
!
Double-click any delimiter.
Xcode selects everything up to and including the matching delimiter.
!
Position the pointer over the focus ribbon.
Xcode highlights the scope at that location.
!
Type a closing brace or other delimiter.
Xcode causes its counterpart to blink.
!
Choose Lditor > Structure > 8alance Delimiter.
Xcode selects the text surrounding the insertion point, up to the nearest set of enclosing delimiters.
Have Pix-it Plag Lrrors as ou Type
when your target is set to use the LLvM compiler, a feature called Pix-it scans your source text as you type.
Correct mistakes with Pix-it as you enter source code.
7e catcb mistakes witb Iix-it . . .
1. |n a target built with the LLvM compiler, open a source file.
2. |ntroduce an error in the code.
3. when a red underbar or a caret appears, click the symbol in the gutter to see the error message.
4. |f Pix-it suggests corrections, select a correction and press Peturn.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
dit Seurce Cede
Lnter Code uickly and Accurately with the Help of the Source Lditor
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
129
Pix-it scans your source text as you type. Pix-it marks syntax errors with a red underbar or a caret at the
position of the error, and a symbol in the gutter. Clicking the symbol displays a message describing the
possible syntax error and, in many cases, offers to repair it automatically. Select a suggested correction and
press Peturn to accept it. Press Lsc to cancel the operation.
To use Pix-it, you must build the target with the LLvM compiler and the indexing of your pro|ect must be
complete. Pix-it works with the C, Ob|ective-C, and Ob|ective-C++ languages.
The video shows correcting a double equals sign in an assignment statement.
7ip: |f there are several Pix-it warnings in a file, you can navigate to the next or previous warning
by choosing Navigate > 1ump to Next |ssue or Navigate > 1ump to Previous |ssue.
Pind and Display Pelated Content
Xcode provides several features that help you find content related to the code you're currently editing: you
can open a file based on a partial string, you can |ump to a symbol definition, you can navigate to related
content using a button in the |ump bar in the primary editor or in a split editor, or you can split the editor and
have Assistant find related content for you.
Open a P|le uickly
Sometimes you may need to open a file whose location you don't know, or you may want to open the file that
defines a particular symbol, such as a variable, method, or class. The Open uickly command finds files that
define a specified symbol or whose filename contains a specified string. Open uickly searches are case
insensitive and limited to the current pro|ect and the active SDK.
7e use tbe Dpen uickIy cemmand
1. Choose Open uickly from the Pile menu.
2. |n the search field, type any portion of the name of the file you want to open or the symbol you want
to find.
dit Seurce Cede
Pind and Display Pelated Content
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
130
7ip: Select a filename or symbol name in the editor and invoke the Open uickly command
to prefill the dialog's search field with the selected text. Or, to open a header file referenced in
a #include or #import statement, place the cursor on the line of the statement and invoke the
Open uickly command to search for the header file.
3. Prom the search results list, double-click the file you want to open, or select the file you want to open
and click Open.
7ip: To open the file in the assistant editor, hold down the Option key when you double-click
or click Open. To open the file in a separate window, hold Option-Shift. To see a dialog letting
you specify where the file should open, hold down Option-Shift-Click. ou can change these
behaviors in the Ceneral preferences pane.
|n filename-based searches, Xcode searches for header files, implementation files, model files, nib files, plist
files, and pro|ect packages. |n symbol-name-based searches, it searches source code files only.
dit Seurce Cede
Pind and Display Pelated Content
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
131
Split the Lditor Area to Display Pelated Content
Xcode allows you to split the editor pane to provide multiple views of the same file or to view multiple files at
once.
To split the editor, open an assistant editor pane by choosing view > Lditor > Assistant or by clicking the
Assistant button in the workspace toolbar (Pigure 5-5).
Iigure 5-5 The Assistant button
7e see tbe same fiIe in eacb pane
1. Open an assistant editor pane.
2. Select Manual from the Assistant pop-up menu ("To set the behavior of the assistant editor" (page
138)).
dit Seurce Cede
Pind and Display Pelated Content
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
132
ou can view any portion of the file in either split plane, and you can edit the file in either pane. Any
changes made in one pane are instantly reflected in the other.
The split can be horizontal (as shown in the figure) or vertical. To change the orientation of the split,
choose view > Assistant Layout.
dit Seurce Cede
Pind and Display Pelated Content
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
133
Customize Keyboard Shortcuts to Determine where a Pile's Contents Are Displayed
Selecting a file in the pro|ect navigator or |ump bar causes that file to open in the normal editor pane. |f Assistant
is set to tracking mode, it tracks the change. 8y default, if you hold down the Option key when selecting a file
in the pro|ect navigator or |ump bar, Xcode displays that file in the Assistant pane rather than the standard
pane. Doing so switches Assistant to manual mode.
ou can customize the behavior of the single click, Option-click, and double-click keyboard shortcuts in the
Ceneral pane of Xcode preferences (Pigure 5-6).
Iigure 5-6 Ceneral preferences
To customize the behavior of keyboard shortcuts for opening a file, open Ceneral Preferences and choose an
option from each navigation pop-up menu. The options include:
!
Primary editor: Opens the file in the primary editor pane in the window and tab already open.
!
Pocused editor: Opens the file in whichever editor pane currently has focus.
!
Single assistant editor: when the navigation originates in a navigator pane or the primary editor (using
the |ump bar or the |ump to definition command), if the assistant editor is not open or is not split, opens
the file in the assistant editor.
dit Seurce Cede
Pind and Display Pelated Content
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
134
|f the assistant editor is split, displays a navigation chooser dialog (Pigure 5-7) showing the current layout
of editor panes in the window that has focus, with the option of selecting any open editor pane or adding
a new one. Double-click your selected pane, or make your selection and press Peturn. Press Lsc to cancel.
Iigure 5-7 The Single Assistant navigation chooser dialog
|f the file is already open in one of the editor panes, the navigation chooser displays a star to indicate the
pane containing the file.
when the navigation originates in an assistant editor pane, Xcode opens the file in the primary editor.
!
Separate assistant editor: |f the assistant editor is closed and is not split, opens the file in the assistant
editor.
|f the assistant editor is open, opens the file in a new assistant editor pane.
|f the assistant editor is split but closed, opens the file in the most-recently-opened assistant editor pane,
replacing the file that was in that pane.
|f the file is already open in an assistant editor pane, switches the focus to that pane.
!
Separate tab: |f the file is not already open in the current window, opens the file in a new tab.
|f the file is already open in another tab in the same window, switches the focus to that tab.
!
Separate window: |f the file is not already open in a separate window, opens the file in a new window.
|f the file is already open in a separate window, switches the focus to that window.
dit Seurce Cede
Pind and Display Pelated Content
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
135
The Option-Shift-Click key combination opens a navigation chooser dialog (Pigure 5-8 (page 136)) showing the
current layout with the options of selecting any open editor pane in any window and any tab, or adding a new
editor pane, window, or tab. Double-click your selection, or make your selection and press Peturn. Press Lsc
to cancel.
Iigure 5-8 The navigation chooser dialog
1ump to a Symbol's Definition
ou can |ump to the definition of a symbol and display it in the primary editor window, in a split editor pane,
in another tab, or in another window.
7e jump te a symbeI's definitien
1. Hold down the Command key., and command-click the symbol in which you're interested.
dit Seurce Cede
Pind and Display Pelated Content
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
136
2. Move the pointer over text to highlight each symbol that can be used as a link to a definition.
3. |f there is more than one definition for the symbol, Xcode displays a list of possibilities. Click the one
you want.
Alternatively, select the symbol in which you're interested and choose Navigate > 1ump to Definition or
Control-click the symbol and choose 1ump to Definition from the shortcut menu.
7ip: Use one of the modifier keys set in the Ceneral pane of Xcode preferences together with any of the
methods described here to open the definition in a split editor pane, a tab, or another window.
dit Seurce Cede
Pind and Display Pelated Content
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
137
Pind Pelated |tems with the 1ump 8ar
Use the related items pop-up menu in the |ump bar (Pigure 1-19 (page 39)) to |ump to files and classes related
to the file you have open. Por example, you can find superclasses and subclasses of the class defined in the
open file, headers included in the file, or headers that include the file. Por a header file you can |ump to the
implementation file, and vice versa.
Pind Pelated Content Automatically
when you open an assistant editor pane, you can set Assistant to either of two modes: tracking (or automatic)
mode or manual mode. Tracking mode has several criteria from which you can choose, such as counterparts,
superclasses, subclasses, or siblings. Assistant selects the file or files that best meet the selected criterion and
opens those files in the assistant editor pane. |n manual mode, you select the file to display by navigating to
it in the |ump bar. ou can split the assistant editor into as many panes as you wish.
7e set tbe bebavier ef tbe assistant editer
1. Open an assistant editor pane.
2. Open the Assistant pop-up menu. The Assistant pop-up menu is the first item to the right of the back
and forward arrows in the assistant editor |ump bar.
3. Make a selection from the menu.
7ip: The choices offered in the Assistant pop-up menu depend on the type of file being edited.
dit Seurce Cede
Pind and Display Pelated Content
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
138
7e spIit tbe assistant editer
1. Click the plus sign at the right end of the assistant editor |ump bar to split the editor.
2. Set each Assistant pane to manual or tracking.
3. Set each tracking pane to a tracking criterion.
The figure shows one file on the left of the split editor pane, the counterpart file in the upper-right
Assistant pane, and another view of the file in the lower-right Assistant pane.
7ip: To change the orientation of the split editor panes, choose view > Assistant Layout.
dit Seurce Cede
Pind and Display Pelated Content
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
139
Use Assistant with |nterface 8uilder and Data Models
when you're using |nterface 8uilder to design a user interface, you can use Assistant to automatically display
the code file most relevant to the interface element you're working with. See "Simultaneously Design and
|mplement User |nterface Ob|ects Using Multiple Lditors" (page 117) for details. Similarly, when you use the
Core Data modeling editor, the assistant editor can display model classes related to the entities in your model
(Pigure 5-9). The Core Data modeling editor is discussed in "Design Data Models Craphically" (page 26).
Iigure 5-9 The assistant editor used with a data model
dit Seurce Cede
Pind and Display Pelated Content
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
140
|ncorporate Other Source Lditor Peatures into our workflow
The source editor provides many features to make it easier to write and maintain your code. This section
highlights a few of these features not described elsewhere in this document.
Lxamine the Structure of our Code with Code Polding
One powerful way to examine the structure of source code is to use the focus ribbon, also called the coJe
lolJ|n t|ooon.
Pocus your attention on a particular method or function in source code by hiding the other parts of the source
code.
7e feId and unfeId seurce cede . . .
1. with a source file open, click anywhere in the source code.
2. Choose Lditor > Code Polding > Pold Methods & Punctions.
3. Navigate to the method you want to unfold.
4. Double-click the ellipsis button to unfold the method.
5. Use the focus ribbon to select the method's scope.
6. Click in the focus ribbon to fold the method.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
The Code Polding submenu provides several options for folding and unfolding code.
The focus ribbon is located between the editor gutter and the source code. Move the pointer into the focus
ribbon to display a scope in the focus box. Then click in the focus ribbon to fold the code in scope.
The video shows the steps for folding all the methods and functions in the source code, unfolding the
method ha1uJa1S1ze, and folding the same method using the focus ribbon.
dit Seurce Cede
|ncorporate Other Source Lditor Peatures into our workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
141
|f you have the option "Pocus code blocks on hover selected in Text Lditing preferences, then you can move
the pointer over the focus ribbon to examine the various scopes of code blocks in a file. |n Pigure 5-10, for
example, the pointer is over the focus ribbon next to an 11 statement and three scopes are indicated by
degrees of shading in the code: the 11 statement, the method (show0Jh1deW1hdow) containing the 11
statement, andthe class implementation(NSW1hdowCoh1Jo11eJ{SKTCohveh1ehce)) containingthe method.
Iigure 5-10 The focus ribbon in use
dit Seurce Cede
|ncorporate Other Source Lditor Peatures into our workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
142
view Preprocessor or Assembly Output
ou can use commands in the Product > Cenerate Output menu to process source files and generate the
preprocessed output (Pigure 5-11) or assembly output.
Iigure 5-11 Preprocessor output
The preprocessor evaluates directives in your source code (instructions starting with the pound sign (#) such
as includes, defines, and conditional logic) and converts them into C code to be sent to the compiler. ou can
examine the preprocessed output to make sure that the logic in your source code is being interpreted by the
preprocessor as you expect in order to debug compilation problems.
The assembly output is the set of instructions that the compiler generated from the preprocessed output. ou
can study the assembly output to see how the instructions were formed or ordered, to seek out better
optimization patterns, or to look for compiler bugs.
dit Seurce Cede
|ncorporate Other Source Lditor Peatures into our workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
143
The output type is also a new category in the assistant editor for a selected primary file (Pigure 5-12).
Iigure 5-12 Cenerated output in Assistant |ump bar
view Documentation for a Symbol Using uick Help
ou use uick Help in the Symbol inspector to get information about AP| symbols, user interface ob|ects, and
build settings.
Pind concise reference documentation for an AP| symbol without moving away from your source file.
7e Ieek up decumentatien fer an API symbeI . . .
1. with a source file open, click the Symbol inspector button in the utility area.
2. Place the insertion point in an AP| symbol in the source editor.
3. view the documentation under uick Help in the Symbol inspector.
4. To view more detailed information, click the AP| name at the top of uick Help.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
dit Seurce Cede
|ncorporate Other Source Lditor Peatures into our workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
144
when you place the insertion point in a symbol, summary reference information appears in the Symbol
inspector in the utility area.
The information includes links to:
!
Complete reference documentation for the symbol
!
The header file where the symbol is declared
!
Pelated programming guides
!
Pelated sample code
AIternative: To view concise reference information for an AP| symbol in a pop-up window,
Option-click the symbol in the source code.
To get information about a symbol when the utility area is closed, you can open a uick Help window by
Option-clicking the symbol ("Pind and Display Pelated Content).
Iigure 5-13 The uick Help window
Pind concise documentation for an ob|ect using uick Help. ou can find concise class reference documentation
for a single ob|ect without taking your focus away from your nib file.
7e Ieek up decumentatien fer an Interface 8uiIder ebject . . .
1. with a nib file open, click the uick Help button.
2. Click the ob|ect about which you want information.
3. view the documentation under uick Help.
dit Seurce Cede
|ncorporate Other Source Lditor Peatures into our workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
145
4. To view more detailed information, click the title of the reference document.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
uick Help offers a persistent location for AP| reference documentation. when you click an ob|ect, uick
Help displays information about that ob|ect.
Por complete reference information about the ob|ect, click the title of the reference document listed in
uick Help. The reference document opens in the Organizer window. ou can also open relevant
programming guides, sample code, and other related documents by clicking their titles in uick Help.
Pind concise documentation for a build setting using uick Help.
7e Ieek up decumentatien fer a buiId setting . . .
1. Click 8uild Settings at the top of the pro|ect editor.
2. Display the Symbols inspector.
3. Select a build setting.
4. view the documentation under uick Help in the Symbols inspector.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
uick Help provides a persistent location for build setting documentation without taking your focus away
from the build settings pane. whenever you select a build setting, uick Help displays information about
that item.
The video shows viewing information on a build setting in Sketch.
dit Seurce Cede
|ncorporate Other Source Lditor Peatures into our workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
146
AIternative: Optiondouble-click a build setting to open uick Help in a separate window.
Unlike uick Help in the utility area, the uick Help window is not persistent.
Automate Lxtensive Changes in our Piles
|n addition to all the features Xcode provides to make it easier to enter and correct your code, there are features
at several scales to help you make changes that apply to more than one line of text. These include Ldit All in
Scope, Search and Peplace, and Pefactor.
Simultaneously modify all the occurrences of a symbol within a scope with the Ldit All in Scope feature. Por
example, you can change the name of a local variable or parameter everywhere in a scope at the same time.
7e edit a symbeI everywbere in a scepe . . .
1. Place the insertion point in the symbol you want to edit.
2. when the pop-up menu appears, select Ldit All in Scope.
3. Ldit the symbol.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
Placing the insertion point in a symbol underlines all occurrences of that symbol in the scope and lets you
see the extent to which it is used.
Choosing Ldit All in Scope from the pop-up menu selects all occurrences of the symbol. As you type new
text, all selections of the symbol change simultaneously.
The videodemonstrates changingthe symbol 1oweJR1gh1to1oweJR1gh1CoJheJwithinthe a11ghedRec1
method.
To find and change all the instances of a text string in a single file, choose Ldit > Pind > Pind and Peplace.
To find and change all the instances of a text string in your pro|ect or workspace, use the Peplace option of
the search navigator (see "Peplace Text Strings" (page 215)).
To refactor code (that is, to change the code without changing its behavior), see "|mprove our Code's Structure
Through Pefactoring" (page 221).
dit Seurce Cede
|ncorporate Other Source Lditor Peatures into our workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
147
|ncorporate Piles and Code from the Xcode Libraries
Xcode provides libraries of file templates and code snippets that you can use in your program. |t also has
libraries of |nterface 8uilder ob|ects and media files that you can use in your nib files. The library pane is in the
lower part of the utility area (see "The Xcode 4 workspace window (page 12)). Lach of the buttons at the top
of this pane selects a category of library ob|ects, as follows:
!
IiIe tempIates range from templates for applications to subclasses of commonly used Cocoa classes. Pile
templates have subcategories, which you can choose from the pop-up menu below the line of buttons.
ou can display the templates as icons only or as icons and text. Drag file and pro|ect templates to the
pro|ect navigator.
!
Cede snippets are short pieces of source code that you can use in your software. To use one, drag it
directly into your source code file. Alternatively, you can select a portion of the code from the code
information pop-up window and drag that into your file. when you create a code snippet, you can add a
completion shortcut, which you can use when editing source code. Type the shortcut and select the
completion shortcut from the completion list to add the code snippet to your file. Note that the new code
snippet is flagged with the word "User.
!
Interface buiIder ebjects are organized with subcategories and provide information pop-up windows
like those for the file templates and code snippets. Depending on the ob|ect, you drag it onto the |nterface
8uilder canvas, into another ob|ect on the canvas, or into the |nterface 8uilder dock. See "Ldit User
|nterfaces" (page 76) for more information on |nterface 8uilder.
!
Media fiIes include all the graphics, icons, sound files, and other media files that you use in your code.
when you're editing an |nterface 8uilder document, the Media library also shows the built-in template
images from NSTmage and sounds provided by the system. |n |nterface 8uilder, you can drag an image
from the library and drop it into your user interface. |nterface 8uilder creates an image view to hold the
dropped image. Alternatively, you can drag an image into an existing button, image view, or any other
ob|ect that can contain an image. ou can set a sound on an NSBu11oh ob|ect.
Add a new file to a pro|ect or workspace using the Pile Template library. This library offers a convenient way
to create files in your pro|ect or workspace.
7e add a new fiIe frem tbe IiIe 7empIate Iibrary . . .
1. Choose Pile Template Library from the Utilities menu under the view menu.
2. Select the file template in the library.
3. Drag the template to a pro|ect or group in the pro|ect navigator.
dit Seurce Cede
|ncorporate Other Source Lditor Peatures into our workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
148
4. Name the file, and click Save.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
The video illustrates using a template fromthe Pile Template library to add an Ob|ective-C class to a pro|ect.
Note that the library button is labeled with a file icon.
Using the provided file templates ensures that certain minimal file characteristics are correct for a file. Por
example, as seen in the video, Xcode automatically creates both the implementation (.m) file and the header
(.h) file for the new Ob|ective-C class.
when you click a template, an information window pops open with information about the use of the template
(Pigure 5-14).
Iigure 5-14 A file template information pop-up window
Add frequently-used source code to your pro|ect by using a snippet from the Code Snippet library.
7e drag a cede snippet te a seurce fiIe . . .
1. with a source file open, click the Code Snippet library button.
2. Select a code snippet.
dit Seurce Cede
|ncorporate Other Source Lditor Peatures into our workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
149
3. Drag the snippet to the source file.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
The system-supplied snippets in the library are designed to speed development and help ensure code
integrity. ou can also create custom code snippets.
The video illustrates using a code snippet to add an 1h11 method to the implementation of an Ob|ective-C
class.
Lxtend the scope of the Code Snippet library by creating custom snippets. The Code Snippet library provides
a number of useful standard snippets. ou can add to this collection by creating your own custom snippets.
7e create a custem cede snippet . . .
1. Open the Code Snippet library.
2. Select some text in a source file and drag it to the library.
3. Open the new custom snippet and click Ldit.
4. Cive the snippet a name and click Done.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
Code snippets let you enter source text with minimum effort. ou can drag a standard or custom code
snippet into a source file. ou can also type a completion shortcut to enter a snippet.
7ip: ou can include tokens in a customsnippet. Por example, the string <#Code#> adds a token
labeled Code in the source text created by the snippet.
Lnter source code text with minimum effort by typing a completion shortcut for a code snippet.
dit Seurce Cede
|ncorporate Other Source Lditor Peatures into our workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
150
7e determine tbe sbertcut fer a cede snippet . . .
1. |n the Code Snippet library, select the snippet for which you want to use a shortcut.
2. Click Ldit.
3. |n the Completion Shortcut field, note the shortcut or add one.
4. Click Done.
Code snippets let you quickly enter source code. ou can drag a snippet from the Code Snippet library into
a source file. Or, for maximum efficiency, type a snippet shortcut in the text of your source code, then press
Lsc and then Peturn to enter the snippet. |n most cases, when you begin typing the snippet's completion
shortcut, Xcode suggests it, so you need only accept it by pressing Peturn. 8oth standard and custom code
snippets support completion shortcuts. ou can edit the shortcut for a custom snippet.
The screenshot shows a completion shortcut highlighted.
Pilter the library items displayed in the selected library by entering text into the search field at the bottom of
the library pane.
dit Seurce Cede
|ncorporate Other Source Lditor Peatures into our workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
151
Use |nspectors to view and Lnter Data
|nspectors are panes in the utility area that you can use to read or enter data about files, |nterface 8uilder
ob|ects, symbols, and data models. Pigure 5-15 shows the Pile inspector.
Iigure 5-15 The Pile inspector
The Symbol inspector is discussed in "viewDocumentation for a Symbol Using uick Help" (page 144). The Pile
inspector and Symbol inspector are always available. Other inspectors appear when appropriate. Por more
information about |nterface 8uilder, see "Ldit User |nterfaces" (page 76).
dit Seurce Cede
|ncorporate Other Source Lditor Peatures into our workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
152
To build and run your app, Xcode uses the settings in your pro|ect and information in a build plan known as
a scleme .
Create, Ldit, and Manage Schemes
|n Xcode, before you build, you select a scheme, which specifies which targets to build, what build configuration
to use, and the executable environment to use when the product specified by the target is launched. ou also
select a run destination. when you create a new Mac OS X pro|ect, Xcode provides a default scheme and two
run destinations: local 32-bit and local 64-bit. Por an iOS application, the run destinations are devices and
simulators.
ou can add as many additional schemes as you want. Por example, you might want one scheme that builds
both your application and a plug-in before running, and another that builds the product without the plug-in.
Or if you have two different but commonly used |nstruments templates, you might have one scheme for
profiling with one of the templates and a different scheme for the other one.
ou use the Scheme pop-upmenu in the upper-left corner of the workspace window("Add8uildConfigurations)
to select a scheme and run destination. Choose the scheme you want to edit and then choose Ldit Active
Scheme from that menu to edit an existing scheme. Choose Manage Schemes to change the list of schemes,
where they're stored, and whether they're shared. Choose New Scheme to add a scheme to your pro|ect.
Alternatively, you can choose Ldit Scheme, New Scheme, or Manage Schemes from the Product menu.
Iigure 6-1 The Scheme pop-up menu
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
153
8uild and Pun our App
The left column of the scheme editing dialog (referred to hereafter for brevity's sake as the scleme eJ|tot ) has
a list of actions you can perform, plus the 8uild item, which you use to determine which targets are built for
each type of action. Lach action can be set to produce either a debug or release build (or, if you've added more
build configurations, those are listed as well). There are options for building, running, testing, profiling (using
|nstruments), analyzing, and archiving your products.
ou can execute scripts and have Xcode send emails before or after a build or any of the actions in the scheme
editor.
7e set up pre- er pest-actiens
1. |n the scheme editor, open the disclosure triangle next to 8uild or any of the actions in the left pane.
2. Click the Add button at the bottom of the right pane and choose New Pun Script Action or New Send
Lmail Action.
3. |n the template that opens, fill in the fields.
The figure shows two pre-run actions: an email that's sent and a script that's executed before the
product is launched.
8uiId and Run eur App
Create, Ldit, and Manage Schemes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
154
4. Por a Pun Script pre-or post-action, if your script needs to access values from target build settings,
choose the target from the "Provide build settings from pop-up menu.
Specify which Targets Are 8uilt for Lach Type of Action
8y default, Xcode creates one scheme per target in your pro|ect or workspace, and the Targets column shows
the target for which the scheme was created. However, you can add as many targets from your pro|ect or
workspace to a single scheme as you wish.
Ldit a scheme to determine which targets are built when you choose Pun, Test, Profile, Analyze, or Archive
from the Product menu.
7e buiId muItipIe targets . . .
1. Prom the Scheme toolbar menu, choose a scheme.
2. Prom the same menu, choose Ldit Active Scheme to display the scheme dialog.
3. |n the left column, select 8uild.
4. Por each target, select the actions for which to build the target.
8uiId and Run eur App
Create, Ldit, and Manage Schemes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
155
5. Click OK.
Targets which are required due to their use in the Pun, Test, or Profile actions cannot be turned off.
Select Parallelize 8uild if you want to build all independent targets at the same time. |f you select this option,
the build is faster but it may not produce correct results unless you set up target dependencies correctly.
The Pind |mplicit Dependencies option is selected by default. Deselect this option if you add a pro|ect to
your workspace that you don't want used automatically.
Pename or Peorganize our Schemes
8y choosing Manage Schemes from the Product menu (or from the Scheme pop-up menu) you can see a list
of all the schemes in the pro|ect. ou can rename or reorganize the schemes in the menu. ou can also specify
whether each scheme should be displayed in the pop-up menu, where the scheme is stored (in the pro|ect or
workspace) and whether the scheme should be shared with others using the pro|ect or workspace.
8uiId and Run eur App
Create, Ldit, and Manage Schemes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
156
The Manage Schemes dialog has four settings for each scheme plus several other controls, as shown in "The
manage schemes dialog.
Iigure 6-2 The manage schemes dialog
The four columns in the Manage Schemes dialog are used as follows:
Displays or hides the scheme in the Scheme menu. Show
Specifies the name of the scheme. ou can edit this name. Scheme
Specifies whether a scheme should be stored in a pro|ectin which case it's available in
every workspace that includes that pro|ector in the workspacein which case it's
available only in that workspace.
Container
Specifies that the scheme is visible to anyone using that pro|ect or workspace (depending
on where the scheme is stored). 8e sure to check with other people using the pro|ect or
workspace before deleting or modifying a shared scheme.
Shared
ou can drag the schemes to reorder their appearance in the dialog and the Scheme menu.
The Add (+) button allows you to create a new scheme or duplicate the selected scheme. The Pemove (-)
button allows you to delete the selected scheme. The Action menu allows you to export the selected scheme
or import an exported scheme.
The Ldit button dismisses this dialog and displays the selected scheme in the scheme editor.
|f the Autocreate schemes checkbox is selected, when you add a newtarget to your pro|ect, Xcode automatically
creates a scheme for it. |f the checkbox is not checked, then you can click the Autocreate Schemes Now button
to have Xcode create new schemes for any targets that don't have them.
8uiId and Run eur App
Create, Ldit, and Manage Schemes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
157
Configure and Lxecute Actions
There are five actions that you can perform with Xcode:
!
Pun
!
Test
!
Profile
!
Analyze
!
Archive
Lach of these actions requires you to first build your code. Lxactly what is built is specified by the scheme you
choose and how that scheme is configured. |n addition to the 8uild pane in the scheme editor, which specifies
which targets are built for each action, there is a configuration pane for each action.
Pun our Application to Debug |t
Although a scheme can specify any number of targets to be built when you click the action button, Xcode can
launch and debug only one executable at a time. "The scheme editor Pun pane shows the |nfo pane for the
Pun action.
Iigure 6-3 The scheme editor Pun pane
8uiId and Run eur App
Configure and Lxecute Actions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
158
ou can specify whether to use a debug or release build configuration (or any other build configurations you
added) and which debugger to use.
Xcode Debuggers
Different debuggers provide different information and error messages. Xcode currently provides the CD8 and
LLD8 debuggers.
Debug vs. Pelease 8uilds
A debug build includes symbols that can be used by a debugger to display your source code when your
program stops at a breakpoint and to show you the values of your variables at that point. Por a release build,
you normally want to strip that information out, because the debug information makes it very easy to
reverse-engineer the program. Pelease builds also typically do code optimization that isn't done for debug
builds. 8ecause the Pun action is normally used for debugging, most developers use a debug build configuration
for the Pun action. However, you might occasionally want to build and run your application with the release
configuration to see what size your application will be and to make sure there are no problems introduced by
the code optimization, that is, to make sure your application runs as you expect.
Arguments and Lnvironment variables
Other panes for the Pun action let you provide arguments and environment variables to pass to your executable
on launch, and a number of diagnostic options, such as for memory management and logging.
Specify runtime arguments for your application when you run it in Xcode.
7e run yeur appIicatien witb arguments . . .
1. Prom the Scheme toolbar menu, choose a scheme.
2. Prom the same menu, choose Ldit Active Scheme to display the scheme dialog.
3. |n the left column, select Pun.
4. To specify runtime arguments, click Arguments.
5. Click OK.
8uiId and Run eur App
Configure and Lxecute Actions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
159
6. Click the Pun button or choose Product > Pun.
Schemes contain a Pun action that affects what happens when you choose Product > Pun. To specify
runtime arguments, click the Arguments tab. ou can specify arguments passed on launch, environment
variables, and modules for which to load debug symbols.
During the test and debug phases of your product development, configure a scheme to run your application
with various memory management diagnostics and logging options enabled. Schemes have a Pun action with
a Diagnostics pane that allows you to choose from a selection of runtime diagnostic tools.
7e run yeur appIicatien witb diagnestics . . .
1. Prom the Scheme toolbar menu, choose a scheme.
2. Prom the same menu, choose Ldit Active Scheme to display the scheme dialog.
3. |n the left column, select Pun.
4. To specify runtime diagnostics, click Diagnostics.
8uiId and Run eur App
Configure and Lxecute Actions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
160
5. Click OK.
6. Click the Pun button or choose Product > Pun.
Select the tools that you want Xcode to use. ou can viewoutput fromthese tools in the debug area console
and in the debug log in the log navigator.
Memory Management options:
!
nabIe ScribbIe. Pill allocated memory with 0xAA and deallocated memory with 0x55.
!
nabIe Cuard dges. Add guard pages before and after large allocations.
!
nabIe Cuard MaIIec. Use 11bgma11oc to catch common memory problems such as buffer overruns
and use-after-free.
!
nabIe 7embie Dbjects. Peplace deallocated ob|ects with a "zombie ob|ect that traps any attempt
to use it. when you send a message to a zombie ob|ect, the runtime logs an error and crashes. ou
can look at the backtrace to see the chain of calls that triggered the zombie detector.
Logging options:
8uiId and Run eur App
Configure and Lxecute Actions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
161
!
Distributed Dbjects. Lnable logging for distributed ob|ects (NSCohhec11oh, NSThvoca11oh,
NS01s1ah10bec1, and NSCohcJe1ePoJ1CodeJ).
!
Carbage CeIIectienActivity. Lnable various logging facilities in the garbage-collected memory allocator.
Log when a collection occurs, log when new regions are allocated, and log all weak reference
manipulations.
!
MaIIec Stack. Pecord stack logs for memory allocations and deallocations.
!
Leg xceptiens. Log Ob|ective-C runtime exception handling.
!
Leg DLD API Usage. Log dynamic-linker AP| calls (for example, d1opeh).
!
Leg Library Leads. Log dynamic-linker library loads.
Debugger options:
!
Step en Debugger() and DebugStr(). Lnable Core Services routines that enter the debugger with a
message. These routines send a S|C|NT signal to the current process.
8uiId and Run eur App
Configure and Lxecute Actions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
162
Location Simulation
|n Xcode 4.2 and later, you can simulate locations other than your current location in iOS applications that use
Core Location. To set a location, choose Ldit Scheme from the scheme selector in the toolbar, select the Pun
action, and click the Options tab. ou can then choose a location fromthe Location menu ("Choosing a location
in the scheme editor). To set a location in the debug bar, see "Set a Location in the Debug 8ar" (page 196).
Iigure 6-4 Choosing a location in the scheme editor
Pun Unit Tests to Pind Pegressions
whenever you make changes to your code, there's a chance that you've introduced bugs and that the code
will no longer run as expected. As a quality control measure, you can create programs, called un|t tests , that
automatically exercise the features of your application and check the results. Lach unit test is a separate bundle
containing code for a set of test cases, each of which exercises some subset of your application's features. Test
cases are organized into test suites. |n code, you create classes that are subclasses of the SehTes1K11 test
suite base class. Lach such class in the bundle is a test suite, and any methods in those classes that begin with
the string 1es1 are the test cases.
8uiId and Run eur App
Configure and Lxecute Actions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
163
Choosing the Test action causes Xcode to build the targets you specified for the test action in the 8uild pane
of the scheme editor and then executes the test cases you enabled in the Test pane. Normally, you create one
or more test targets that are separate from your application product targets.
The Xcode development installation includes a framework for testing Ob|ective-C codethe senTestingKit
frameworkwhich provides methods you can use to exercise methods in your code and test the results.
Por references and more reading on unit tests and the senTestingKit framework, see the Sen:te website.
7e incIude unit tests wben yeu create a new preject
1. Choose Pile > New > New Pro|ect and select the |nclude Unit Tests option in the Choose Options pane
of the New Pro|ect dialog.
2. Select the |nclude Unit Tests option in the Choose Options pane of the New Pro|ect dialog.
The |nclude Unit Tests option is available for both Mac OS X and iOS pro|ects. when you select this option,
Xcode provides your pro|ect with a test target and with header and implementation template files that use
the senTestingKit framework.
|f you want to add unit tests to an existing pro|ect, you need to first add a target for the tests and then add
your source code to the target.
8uiId and Run eur App
Configure and Lxecute Actions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
164
7e add unit tests te an existing preject
1. Select the pro|ect in the pro|ect navigator to open the pro|ect editor.
2. Click the Add Target button at the bottom of the editor pane.
3. |n the Other category of templates, select a bundle template for your pro|ect:
!
Por Mac OS X, select the Cocoa Unit Testing 8undle template.
!
Por iOS, select the Cocoa Touch Unit Testing 8undle template.
4. Click Next.
5. Specify a name for the test set and click Next.
6. |n the confirmation dialog, make sure you've selected the correct pro|ect to which you're adding the
target and click Save.
Note that you can select several or all of your class implementation files in the pro|ect navigator (use
Command-click for discontinuous selections) and set their target memberships all at once.
|f you want to add additional test sets to your test target, you can drag an Ob|ective-C test case class file from
the Pile Template library into your pro|ect navigator. Add the file to your test target, not to the application
target, as the file links correctly only if it's in the test target. Note that dragging a test case class file from the
Pile Template library into your pro|ect does not add a test target to your pro|ect.
8uiId and Run eur App
Configure and Lxecute Actions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
165
Having created a test target with one or more test class template files, it's time to write your unit tests and run
them.
7e write and run yeur unit tests
1. |n the header file for your test class, import any headers from your pro|ect that declare methods that
your tests will exercise.
2. Define your test methods in the test class implementation file.
3. Add the source implementation files for any of your pro|ect's classes exercised in your tests to your
test target by selecting the target's checkbox in the Target Membership section of the Pile inspector.
4. Select the scheme you want to use to run the tests in the Scheme pop-up menu and choose Ldit Active
Scheme from that menu.
5. Add your test target to the scheme by clicking the Add (+) button at the bottom of the 8uild pane of
the scheme editor.
8uiId and Run eur App
Configure and Lxecute Actions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
166
6. Make sure the Test checkbox for the test target is selected (as shown here).
7. |n the Test pane of the scheme editor, select each test you want to run.
8. Choose Product > Test to run the tests.
8uiId and Run eur App
Configure and Lxecute Actions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
167
9. Pead your tests' console output in the Console pane of the debug area (or in the test log in the log
navigator).
Lach test case is a method in your test class and can be individually selected or deselected in the Test pane
of the scheme editor. The Test action is enabled after you have at least one test case defined and selected.
Profile our Application to Pind Problems and Optimize our Code
ou can profile your application in order to find problems and optimize your code. Do so using the built-in
|nstruments application. |nstruments runs your executable, collecting and displaying data that you can use to
find problems such as memory leaks and unguarded file system access. |t also helps you optimize aspects of
execution, such as CPU use, file activity, and the use of threads. There are also specialized instruments for
specific frameworks such as Core Data and OpenCL. Although you can run individual instruments, it's common
to run sets of instruments together, such as several instruments that monitor overall system activity. The
|nstruments application comes with a set of templates, each of which includes one or more instruments. ou
can also define your own templates. Por more information on the |nstruments application and instruments
templates, see lnsttuments uset Cu|Je .
ou use the scheme editor's profile pane to specify which template |nstruments should use when you choose
the Profile action.
7e specify an Instruments tempIate fer tbe PrefiIe actien
1. Open the scheme editor.
8uiId and Run eur App
Configure and Lxecute Actions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
168
2. Select the Profile pane.
3. Choose an instrument template from the |nstrument pop-up menu.
The default choice is Ask on Launch, which causes |nstruments to display its template chooser dialog
when it starts up.
|f you select a blank template from the |nstruments template chooser, you can drag one or more individual
instruments into the |nstruments windowto be run with your application. ou can save the set of instruments
as a custom template, in which case it becomes available as a choice in the |nstrument pop-up menu of
the Profile pane.
Perform Static Analysis To Pind Semantic Problems
The Analyze action performs a static analysis of your code. The only option for the Analyze action in the scheme
editor is whether to analyze a debug or release build. To specify which targets should be included in the
analysis, use the checkboxes in the Analyze column of the 8uild pane. Static analysis is discussed in "Locate
Possible Semantic Problems" (page 181).
Create an Archive for Sharing or Submitting our Program
The Archive action creates an application bundle you can use to share your program with others or to submit
your application to the App Store. 8ecause it's unusual to share a debug version of an application, most
developers set the build configuration to Pelease in the Archive pane of the scheme editor. To distribute
frameworks, plug-ins, and other targets with your application, select the checkboxes for those targets under
8uiId and Run eur App
Configure and Lxecute Actions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
169
the Archive column in the 8uild pane of the scheme editor. ou probably don't want to distribute unit tests
with your application, on the other hand, so you should not select the checkbox for the test target in the
Archive column.
Por more information on the use of archives, see "Distribute our App" (page 284).
|nitiate an Action
ou can initiate an action in several ways.
7e initiate an actien
Do one of the following:
!
Click and hold the action button at the left end of the toolbar, then choose the action you want from
the pop-up menu.
|f you click this button without holding it, Xcode initiates the action currently displayed by the button.
!
Choose an action from the Product menu.
!
Use a keyboard shortcut.
There are keyboard shortcuts for every action except Archive (open the Product menu to see the list).
7ip: Hold down the Option key to see additional shortcuts.
The action button and each of the items at the top of the Product menu (Pun, Test, Profile, Analyze, Archive)
cause the targets specified by the 8uild pane of the scheme to be built before performing the specified action.
Other items in the menu allow you to build without other actions, or to perform the other actions using the
last build without building again.
8uiId and Run eur App
Configure and Lxecute Actions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
170
7e epen tbe scbeme editer befere initiating an actien
1. Hold the Option key when you choose the action.
The scheme editor opens to give you the opportunity to check or change the scheme settings before
you run the application.
The OK button at the bottomof the scheme editor is replaced with two buttons: the name of the action
(here, Profile) and Done.
2. Click the action button in the scheme editor.
Any changes you made to the scheme are saved and the action is carried out using the new settings.
7ip: Click Done to save any newscheme settings and close the scheme editor without building
the application.
8uiId and Run eur App
Configure and Lxecute Actions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
171
Customize our 8uild and Pun workflow
ou can specify behaviors that affect your build and run workflow through the Xcode 8ehaviors preferences.
The 8ehaviors preferences pane lets you specify what should happen when a variety of events occur ("8ehaviors
preferences)including, but not limited to, scheme actions.
Iigure 6-5 8ehaviors preferences
Por example, you can have Xcode display the debug area when your code pauses at a breakpoint, or Xcode
can display the issue navigator when a build fails. |f you are searching for text or a symbol name in a large
pro|ect, you can set preferences to let you knowwhen the search has completed, either with or without results.
7ip: |n addition to the 8ehaviors preferences setting to create a snapshot, you can specify that Xcode create a
snapshot before a mass editing operation such as a refactoring transformation. To do so, select the Snapshots
pane in the Pile > Pro|ect Settings or Pile > workspace Settings dialog.
ou can name a tab and specify that tab as the display to use when an event occurs. Then you can set up the
display in that tab exactly as you want it. |f the tab doesn't exist when the alert is triggered, Xcode creates the
tab for you, set up as it was when you created it. Por example, in "8ehaviors preferences, Xcode is configured
to play a sound and open a tab named SketchDebug when the run pauses (such as when a breakpoint is
8uiId and Run eur App
Customize our 8uild and Pun workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
172
triggered). The tab will have the debug area and debug navigator open. |f you configure the tab to include an
assistant editor and to display the debug area with the log pane closed, then every time a breakpoint is
triggered, a tab named SketchDebug opens with those characteristics.
7e name a tab
!
To give a custom name to a tab, double-click the title of the tab and type the new name.
Tab names are case sensitive in the Show Tab field of the 8ehaviors preferences.
Xcode remembers the state of the named tabincluding which window it was inwhen it reopens the tab.
8y naming a tab in a separate window, you can use the "Show tab option in 8ehaviors preferences to
automatically open a new window.
7e autematicaIIy epen a new windew
1. Open and name a new tab.
2. Drag the tab out of the workspace window to create a new window.
3. Set up the new window exactly as you want it.
4. |n 8ehaviors preferences, select the event for which you want the new window to open.
5. Por that event, select the Show tab checkbox and type the name of the tab.
ou can also can design custom behaviors that are triggered by menu items or their key equivalents.
7e create a custem bebavier
1. |n the 8ehaviors preferences pane, click the plus button at the bottom of the left column.
8uiId and Run eur App
Customize our 8uild and Pun workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
173
2. type the name of the new behavior and press Peturn.
3. Select checkboxes to specify what should happen when you invoke this behavior.
Por example, you can create a "Unit Testing" behavior that creates a snapshot and runs your unit tests. After
you've created a behavior, it appears in the Xcode > 8ehaviors menu.
ou can assign a key equivalent for each of your custom behaviors.
8uiId and Run eur App
Customize our 8uild and Pun workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
174
7e assign a key equivaIent te a custem bebavier
1. |n the Key 8indings preferences pane, select the Customized tab to find the behavior for which you
want to assign a key equivalent.
2. Click the Key column on the line of the behavior in order to open a text field.
3. with the text field selected, press the keys you want to use for the key binding.
4. Click outside the text field to complete the operation.
Nete: |f you don't click outside the text field and instead press a key (such as Peturn), Xcode
enters the key you pressed into the text field.
8uiId and Run eur App
Customize our 8uild and Pun workflow
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
175
7ip: |f the key binding you specify conflicts with another, a red circle with an exclamation mark appears at
the right edge of the key column. Xcode does not save the new key binding until you resolve the conflict.
Click the Conflicts tab to see the other command or commands that use the same key combination.
Pine-Tune our 8uilds
Most developers can get by with the default build settings, except for the few that must be setor at least
checkedfor every pro|ect (see "Set the 8asic 8uild Settings" (page 69)). ou may have special needs, however,
that require anything from tweaking a setting or two to creating an entirely new build configuration. To check
or change build settings, click the pro|ect in the pro|ect navigator to open the pro|ect editor. Control-click in
the left column of the pro|ect editor where the pro|ects and targets are listed to see a list of pro|ect editor help
topics ("Pro|ect editor help topics).
Iigure 6-6 Pro|ect editor help topics
ou can edit build settings at the pro|ect or target levels. Most build settings have a system default. |f you click
Levels in the build settings header bar, Xcode shows you the resolved value for each build setting and indicates
with green highlighting the level at which the value was set.
Customize aspects of your product's build process by editing its build settings.
8uiId and Run eur App
Pine-Tune our 8uilds
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
176
7e edit a buiId setting . . .
1. |n the pro|ect editor, select the pro|ect or target whose build setting you want to edit.
2. Click 8uild Settings at the top of the pro|ect editor.
3. Locate the build setting in the left column.
4. Set the value for the build setting in the right column.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
ou set build settings at either the pro|ect level or the target level. To see all the levels of build settings,
select Levels rather than Combined.
The lowest level at which a build setting is defined takes precedence. |f you define a build setting at the
pro|ect level, the definition is set for the corresponding pro|ect, and it's applied to all the targets that belong
to that pro|ect. |f you define a build setting at the target level, the definition applies only to the corresponding
target.
Definitions applied at the target level override definitions set at the pro|ect level. The level at which the
build setting is defined is highlighted in green. Por example, at the beginning of the video, the Architecture
build setting is highlighted in green at the default level. At the end of the video, after the setting has been
redefined at the target level, the Architecture build setting is highlighted in green at the target level.
|f you have changed or customized a setting, it's shown in boldface.
The video shows changing the compiler build setting for a target.
ou can see documentation on a build setting in the Symbol inspector in the utility area.
Pind concise documentation for a build setting using uick Help.
7e see decumentatien en a buiId setting . . .
1. Click 8uild Settings at the top of the pro|ect editor.
2. Display the Symbols inspector.
3. Select a build setting.
8uiId and Run eur App
Pine-Tune our 8uilds
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
177
4. view the documentation under uick Help in the Symbols inspector.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
uick Help provides a persistent location for build setting documentation without taking your focus away
from the build settings pane. whenever you select a build setting, uick Help displays information about
that item.
The video shows viewing information on a build setting in Sketch.
AIternative: Optiondouble-click a build setting to open uick Help in a separate window.
Unlike uick Help in the utility area, the uick Help window is not persistent.
Control the Order in which Xcode 8uilds our Products
Xcode detects when one of your products is dependent on another and automatically builds them in the
correct order. However, in the unusual event that you need to control the order in which Xcode builds your
products, you can create explicit target dependencies by using the 8uild Phases pane of the pro|ect editor.
Lnsure that targets are built in the proper order using target dependencies. |n a complex pro|ect, you may
have several targets that create related products. Prequently, these targets need to be built in a specific order.
7e ensure preducts are buiIt in tbe cerrect erder . . .
1. |n the pro|ect editor, select the target to which you want to add a dependency.
2. Click 8uild Phases at the top of the pro|ect editor.
3. Open the Target Dependencies section.
4. Click the Add (+) button to add a target dependency.
8uiId and Run eur App
Pine-Tune our 8uilds
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
178
5. Select a target from the list and click Add.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
Por example, a pro|ect for a client-server software package may contain targets that create a client application,
a server application, tools that provide command-line interfaces to the client and server, and a private
framework that all the other targets use. Por the pro|ect to build correctly, the private framework needs to
be built before the other targetsthat is, the other targets have a dependency on the private framework.
The video illustrates adding a private framework to the client application target's dependency list.
The 8uild Phases pane of the pro|ect editor also lets you specify the order in which files are compiled and
linked, specify which bundle resources are copied and in what order, and so forth. ou can drag the build
phases into a different sequence if you wish, and you can drag the individual files in each build phase into
whatever order you want. Doing so is advisable only if you have a good reason to do so and knowexactly what
you're doing.
8uiId and Run eur App
Pine-Tune our 8uilds
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
179
Xcode provides all the facilities you need to analyze and debug your code in the workspace window. This
chapter summarizes those facilities.
Select a Debugger
Xcode comes with CD8 and LLD8 debuggers, with CD8 selected by default.
LLD8 is a debugger that is part of the LLvM open source compiler pro|ect (see the LLvM home page at
http://llvm.org/). with few exceptions, the user interfaces for debugging are identical for the two debuggers.
7e cbange tbe debugger
1. Prom the Scheme pop-up menu, choose Ldit Active Scheme.
2. |n the leftmost column of the scheme editor, select the Pun action.
3. |n the |nfo pane, choose the debugger you want to use from the Debugger pop-up menu.
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
180
Debug our App
Pind Coding Mistakes
At any time in your code development, you can run the static analyzer to find potential semantic problems in
your code. |n addition, when you build your pro|ect, the compiler returns messages, warnings and errors that
you can use to find and correct mistakes in your code.
Note that if you use the LLvM compiler, Pix-it scans your code and flags possible errors as you type ("Have
Pix-it Plag Lrrors as ou Type" (page 129)).
Locate Possible Semantic Problems
Use static analysis to examine the semantics of your code to find potential problems with your program logic.
Xcode lets you perform the analysis, examine the results, and edit your source files all within the workspace
window.
ou run the static analyzer by selecting the pro|ect you want to analyze in the pro|ect navigator and then
choosing Analyze from the Product menu. ou can use the 8uild pane of the scheme editor to specify which
targets are included in the analysis.
7ip: |f you want to open the scheme editor to set options before running the static analyzer, hold the Option
key while choosing Product > Analyze.
Pind flawspotential bugsin the source code of a pro|ect with the static analyzer built into Xcode. Source
code may have subtle errors that slip by the compiler and manifest themselves only at runtime, when they
could be difficult to identify and fix.
7e perferm static cede anaIysis . . .
1. Choose Product > Analyze.
2. Select an analyzer message in the issue navigator.
3. Click the corresponding message in the source editor.
4. Use the pop-up menu in the analysis results bar above the edit area to study the flow path of the flaw.
5. Ldit the code to fix the flaw.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
Debug eur App
Pind Coding Mistakes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
181
The Xcode static analyzer parses the pro|ect source code and identifies these types of problems:
!
Logic flaws, such as accessing uninitialized variables and dereferencing null pointers
!
Memory management flaws, such as leaking allocated memory
!
Dead store (unused variable) flaws
!
AP|-usage flaws that result from not following the policies required by the frameworks and libraries
the pro|ect is using
ou can suppress false positive messages fromthe analyzer using assertions, attributes, or pragma directives.
when you analyze a pro|ect for the first time, you may uncover a lot of issues. 8ut if you run the static
analyzer regularly and fix the flaws it uncovers, you should see fewer problems in subsequent analyses.
Analyze early, analyze often. |t's good for the code.
Note that if the static analyzer reports no problems, you can't assume that there are none. The tool cannot
necessarily detect all the flaws in the source code.
The video shows the process of looking at a flaw in the source file SKTTex1.m.
Debug eur App
Pind Coding Mistakes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
182
7ip: Choose Product > Clean to remove the analyzer messages from the issue navigator.
Locate and Display 8uild |ssues
ou can build and run the executable specified by the active scheme by clicking the action button at the left
end of the toolbar. Other options, such as running without building or building without running, are available
in the Product menu.
Iigure 7-1 The issue navigator
|f the compiler finds any problems while building, the issue navigator opens. ou can display problems by file
or by type (Pigure 7-1). Pilters at the bottom of the navigator let you display only issues from the latest build,
only issues associated with the current scheme, only errors (suppressing any warnings), or only issues that
include text matching a string you enter in the filter field.
7e navigate tbreugb buiId issues
Do one of the following:
!
Use the issue pop-up menu at the right end of the |ump bar.
Debug eur App
Pind Coding Mistakes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
183
The issue menu appears as a yellow triangle if the most serious issue listed is a warning ( ) or as a
red octagon if any errors are listed ( ). Choose an error from the menu or use the arrows to cycle
through the errors.
!
Select any of the errors or warnings in the issue navigator to display in the source editor the line of
code where the problem was discovered.
Click the number at the right margin of an issue to see a list of all the issues associated with the line
of code.
Debug eur App
Pind Coding Mistakes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
184
7e view buiId issues witb tbe Ieg navigater
1. Select a build in the build log.
The build results are displayed in the editor area.
2. Open an assistant editor and set it to Peferenced Piles.
3. Select an issue in the log to see it displayed in the assistant editor.
Debug eur App
Pind Coding Mistakes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
185
4. Double-click an issue in the log to see it displayed in a separate window or tab (depending on the
double-click setting in the Ceneral pane of Xcode Preferences).
whereas the issue navigator is the common place to go to see build errors and warnings, build logs are where
you can see details about what happened during a build. Por example, if you want to make sure files were
built in the right order, ensure that a particular file got rebuilt, or track down some advanced pro|ect
configuration problem, you can get the information you need in the build log.
7e view buiId resuIt detaiIs
Do one of the following:
!
Click the list icon ( ) at the end of a build command line in the build log to see the full build command
and results.
!
Option-click a build issue to open the full build results to that issue.
The issue highlights briefly when the full build results open.
Debug eur App
Pind Coding Mistakes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
186
As of Xcode 4.1, you can select what kind of content to view when debugging: source only (when available),
disassembly only, or source and disassembly. The disassembly is the set of assembly-language instructions
seen by the debugger while your program is running. viewing the disassembly can give you more insight into
what your code is doing when it's stopped at a breakpoint. 8y viewing the disassembly and source code
together, you can more easily relate the instruction being executed with the code you wrote.
7e view disassembIy wbiIe debugging
Do one of the following:
!
Choose Product > Debug workflow > Show Disassembly when Debugging.
The disassembly is displayed in the editor pane.
!
Open an assistant editor and choose Disassembly from the Assistant pop-up menu in the assistant
editor |ump bar.
The source and disassembly are shown in the split editor pane.
Debug eur App
Pind Coding Mistakes
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
187
Manage 8reakpoints
Although you can use the debugger to pause execution of your program at any time and view the state of the
running code, it's usually helpful to set breakpoints before running your executable so that you can stop at
known points and view the values of variables in your source code.
Add and Activate 8reakpoints
To set breakpoints, open a source-code file and click in the gutter next to the spot where you want execution
to stop. when you add a breakpoint to the code, Xcode automatically activates breakpoints, as indicated by
the breakpoint-state button in the toolbar (active: inactive: ). ou can toggle the state of breakpoints
at any time by clicking the breakpoint-state button. ou can also disable an individual breakpoint by clicking
its icon. To remove a breakpoint completely, drag it out of the gutter.
ou can set several options for each breakpoint, such as a condition, the number of times to pass the breakpoint
before it's triggered, or an action to perform when the breakpoint is triggered.
7e set breakpeint actiens and eptiens . . .
1. |n the breakpoint navigator, Control-click the breakpoint, and choose Ldit 8reakpoint fromthe shortcut
menu.
2. Set the actions and the options for the breakpoint in the breakpoint editor.
Specify what Xcode does when a breakpoint is triggered with the breakpoint editor.
Lach breakpoint type has specific properties that define it, such as condition and ignore count (for file line
breakpoints), symbol name (for symbolic breakpoints), and exception type (for exception breakpoints). 8ut
all breakpoint types share two properties:
!
Actien: Specifies what actions Xcode performs when the breakpoint is triggered. ou can have Xcode
execute an AppleScript script or a shell or debugger command, log or speak a message, or emit a
sound.
Debug eur App
Manage 8reakpoints
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
188
!
Dptiens: Specifies additional breakpoint behavior, such as whether to continue program execution
after performing actions.
The screenshot shows a file line breakpoint that is ignored the first five times it is hit. Subsequent hits trigger
the breakpoint, which causes Xcode to emit a sound and continue program execution.
|n addition to conditional breakpoints, which are triggered when a specific condition is met, you can create
breakpoints that are triggered when a specific type of exception is thrown or caught, and symbolic breakpoints,
which are triggered when a specific method or function begins execution.
Add an exception breakpoint to your pro|ect in the breakpoint navigator.
7e add an exceptien breakpeint . . .
1. |n the bottom-left corner of the breakpoints navigator, click the Add button.
2. Choose Add Lxception 8reakpoint.
3. Choose the type of exception from the Lxception pop-up menu.
4. Choose the phase of the exception handling process at which you want program execution to stop.
5. Click Done.
The Lxception pop-up menu specifies the type of exceptions on which you want execution to stop:
!
AII. Stops on all exceptions.
!
Dbjective-C. Stops on Ob|ective-C exceptions.
!
C++. Stops on C++ exceptions.
To stop on a particular C++ exception, specify the exception name.
The screenshot shows the properties of an exception breakpoint.
7e add a symbeIic breakpeint . . .
1. |n the bottom-left corner of the breakpoint navigator, click the Add button.
Debug eur App
Manage 8reakpoints
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
189
2. Choose Add Symbolic 8reakpoint.
3. Lnter the symbol name in the Symbol field.
4. Click Done.
Add a symbolic breakpoint to your pro|ect in the breakpoint navigator. Symbolic breakpoints stop program
execution when a specific function or method starts executing.
ou can specify the symbol as:
!
A method name. Por example, pa1hs^a1ch1hgEx1ehs1ohs:.
!
A method of a particular class. Por example, [SKTL1he dJawhahd1esThv1ew],
peop1e::PeJsoh::hame{).
!
A function name. Por example, _obc_msgFoJwaJd.
|f the symbol is declared in more than one library, enter the name of the appropriate library in the Module
field.
The screenshot shows the properties of a symbolic breakpoint.
Ldit 8reakpoints
Por existing breakpoints, you can edit options or change their scopethat is, the pro|ect or workspace in which
the breakpoint appears.
7e edit breakpeint eptiens
1. Open the breakpoint navigator and Control-click the breakpoint whose options you want to edit.
2. Prom the shortcut menu, choose Ldit 8reakpoint.
Debug eur App
Manage 8reakpoints
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
190
3. |n the Condition field of the options dialog, specify an execute condition for the breakpoint (if any).
The breakpoint is triggered only if the condition is true (for example, i 24). ou can use any variables
that are in the current scope for that breakpoint.
ou must cast an function calls to the appropriate return type.
4. Specify values for any other actions you want to set and click Done.
8y default, a new breakpoint is local to the workspace you have open. |f you add the pro|ect containing that
breakpoint to another workspace, the breakpoint is not copied to the newworkspace. ou can assign breakpoints
to other scopes, however. |f you move a breakpoint to User scope, it appears in all of your pro|ects and
workspaces. |f you move a breakpoint to a specific pro|ect, then you see this breakpoint whenever you open
that pro|ect, regardless of which workspace the pro|ect is in.
7e cbange tbe scepe ef a breakpeint
1. |n the breakpoint navigator, select the breakpoint or breakpoints you want to assign to a new scope.
2. Control-click one of the breakpoints, and from the shortcut menu, choose Move 8reakpoints To.
Debug eur App
Manage 8reakpoints
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
191
3. |f you have a workspace window open, your choices include workspace, User, and all of the pro|ects
in the workspace:
|f you have a pro|ect open without a workspace, your choices are User and the pro|ect you have open:
4. Choose workspace to have the breakpoint appear only in this workspace. Choose User to have the
breakpoint appear in all your workspaces and bare pro|ects. Choose a specific pro|ect to have the
breakpoint appear whenever that pro|ect is open, regardless of which workspace it's in.
5. our choice is reflected in the organization of the breakpoint navigator.
Share 8reakpoints
ou can share any breakpoints with other users.
Debug eur App
Manage 8reakpoints
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
192
7e sbare breakpeints
1. |n the breakpoint navigator, select the breakpoint or breakpoints you want to share.
2. Control-click one of the breakpoints, and from the shortcut menu, choose Share 8reakpoints.
3. Xcode moves the shared breakpoints into their own category in the breakpoint navigator:
Abreakpoint with User scope cannot be shared. |f you select a User breakpoint and choose Share 8reakpoint
fromthe shortcut menu, Xcode moves the breakpoint to the local (workspace or individual pro|ect) category
and shares it.
Set Preferences for 8reakpoint 8ehavior
The "Pun pauses option in 8ehaviors preferences specifies what Xcode does when a breakpoint is triggered
and the running application pauses. 8y default, Xcode opens the debug navigator and debug area, showing
the location of the breakpoint in your code and the status of the application's threads and stacks. However,
you can customize this behavior, specifying various sorts of behaviors (such as a sound or announcement),
which navigator to open, and whether to navigate to the first new issue. ou can even design a tab with the
layout you prefer, name the tab, and have Xcode re-create it when a breakpoint is triggered. Por more
information on 8ehaviors preferences, see "Customize our 8uild and Pun workflow" (page !).
Debug eur App
Manage 8reakpoints
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
193
Customize the Debug Area
|f you pause execution or a breakpoint is triggered, the debug area opens, displaying the values of variables
and registers plus the debug console (Pigure 7-2). ou can use the buttons at the right end of the debug area
toolbar to display both the variables and console panes or to hide either one.
Iigure 7-2 The debug area
The variables Pane
The variables pane displays variables and registers. ou specify which items to display using the pop-up menu
in the top-left corner of the variables pane:
!
Auto displays only the variables you're most likely to be interested in, given the current context.
!
Local displays local variables.
!
All displays all variables and registers.
Debug eur App
Customize the Debug Area
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
194
Use the search field to filter the items displayed in the variables pane.
The Console Pane
The console pane displays program output and lets you enter commands to the debugger tool. ou specify
the type of output the console displays with the pop-up menu in the top-left corner of the console pane:
!
All Output displays target and debugger output.
!
Debugger Output displays debugger output only.
!
Target Output displays target output only.
Control Program Lxecution
when you execute a program from Xcode, the debug bar appears at the bottom of the editor pane. ou can
use the debug bar to control program execution and to navigate through threads and stacks. ou can also
step through code and control execution in the source editor and you can suspend a thread in your running
application.
To make it easier to debug full-screen applications, you can set Xcode to a window-in-front mode that lets you
control program execution without obscuring your program window.
Step Through Code with the Debug 8ar
The debug bar includes buttons to:
!
Open or close the debug area
!
Pause or resume execution of your code
!
Step over, that is, execute the current line of code and if it is a routine) return to the next line in the current
file
!
Step in, that is, execute the current line of code and (if it is a routine) |ump to its first line
!
Step out of a |umped-to routine, that is, complete the current routine and step to the next routine or back
to the calling routine
Control-click to step through your code by assembly language instruction instead of by statement. The step
icons change to show a dot rather than a line under the arrow.
Control-Shift-click to perform the action in the active thread while holding other threads stopped. The step
icons show a dashed rather than solid line under the arrow.
Debug eur App
Control Program Lxecution
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
195
7ip: To see which key combination performs which action, look in the Product > Debug menu while a debugging
session is in process.
Set a Location in the Debug 8ar
if you are running an application for iOS 5.0 or later that uses Core Location, the debug bar has a location
drop-down menu (Pigure 7-3). To set a location in the Pun action of the scheme editor, see "Location
Simulation" (page !).
Iigure 7-3 Choosing a location in the debug bar
Step Through Code in the Source Lditor
while your code is paused at a breakpoint or because you clicked the pause button, you can continue execution
or step through your code in the source editor.
To continue execution to a specific line of code, hold the pointer over the gutter next to the target code line
until the continue-to-here icon appears, then click the icon.
Debug eur App
Control Program Lxecution
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
196
To step to the next instruction, hold the pointer over the gutter next to the instruction pointer until the step-over
icon appears, then click the icon.
Suspend a Thread
Suspend a thread to prevent it from running during your debugging session. ou might suspend a thread if
the thread is about to crash or if you want to prevent it from doing work that could interfere with the rest of
your application.
7e suspend a tbread in yeur running appIicatien . . .
1. Pause your application's execution, or wait for it to hit a breakpoint.
2. |n the Debug navigator, Control-click the desired thread.
Debug eur App
Control Program Lxecution
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
197
3. |n the contextual menu, choose Suspend Thread.
A suspended thread does not run when you step through your code or continue execution. The debug
navigator places a red status icon next to suspended threads.
To resume a thread that is currently suspended, Control-click it and select Pesume Thread fromthe contextual
menu.
The screenshot shows the Suspend Thread command in the contextual menu of the debug navigator.
Debug eur App
Control Program Lxecution
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
198
Impertant: Although suspending threads can help you debug your application, it can also have other
consequences. Por example, suspending a thread that holds a lock could cause other threads to deadlock.
Set Xcode window 8ehavior
when you run your application from Xcode in order to debug it, you have both Xcode and your application
open on your monitor. |n some casesfor example, when you have a full-screen application and only one
monitoryou might want to keep Xcode behind your application and use keyboard shortcuts to control
windowexecution. Choose Product >window8ehavior >Xcode 8ehind to keep Xcode behind your application.
|f you need to be able to see the debug area and other debugging information when you stop your application
or it pauses at a breakpoint, however, you can instead choose Product > window 8ehavior > Xcode |n Pront
to keep Xcode in front of your application. |n this case, while your application is running, the Xcode application
shrinks to a minimum size, displaying a minimum set of controls. |n Pigure 7-4, the Xcode window is indicated
with a red box.
Iigure 7-4 Xcode |n Pront window mode while the executable is running
Click the Console button to open the debug console while the application is running. Click the Pocus button
to allow the focus to switch between the application and Xcode.
Debug eur App
Control Program Lxecution
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
199
when you pause execution or your programhits a breakpoint, Xcode expands to showthe debug pane (Pigure
7-5). when you continue execution, Xcode shrinks again.
Iigure 7-5 Xcode |n Pront window mode while the executable is paused
Lxamine Threads, Stacks, variables, and Memory
when you pause execution of your code (see "Control Program Lxecution" (page 195)) or the running code
triggers a breakpoint, Xcode opens the debug navigator, displaying the threads that were running when
execution paused. Under each thread is the stack at that point in program execution. ou can examine the
threads and stacks in the debug navigator, using the filters at the bottom of the navigator to control the scope
of threads and stacks so you can concentrate on the level of detail that is most useful to you. ou can also
navigate through threads and stacks in the debug bar of the debug area.
ou can view variable values in the debug area or source editor, and you can use the debug area and editor
pane together to view the contents of memory locations.
7e view tbreads and stacks in tbe debug navigater
1. Set breakpoints at the locations where you want to examine threads and stacks.
2. Choose Pun from the Product menu (or click the Pun button).
3. when execution pauses, select a stack frame in the debug navigator.
The corresponding source file or disassembled ob|ect code is shown in the source editor.
Debug eur App
Lxamine Threads, Stacks, variables, and Memory
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
200
The slider at the bottom of the debug navigator controls how much stack information the threads and
stacks navigator displays. At the left end of the slider, the debug navigator shows only the top frame
of each stack. At the right end, it shows all stack frames. Click the button at the left end of the slider (
) to toggle between displaying all the active threads or only threads that have your code in them (as
opposed to system library code). The figure shows the debug navigator when execution has stopped
at a breakpoint.
7e view tbreads and stacks in tbe debug area . . .
1. with the debug area open, run your application.
2. Pause your application's execution, or wait for your code to stop at a breakpoint.
3. Choose a thread from the pop-up menu in the debug bar.
4. Lxamine the corresponding source or assembly code.
Debug eur App
Lxamine Threads, Stacks, variables, and Memory
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
201
The debug area lets you examine the threads and stacks of a program being debugged. when you select
a thread or a stack within a thread in the debug bar, Xcode displays the corresponding source file or assembly
code in the main editor.
The screenshot shows the debug area while choosing a thread and a stack frame to examine.
AIternative: ou can also view threads in the debug navigator.
Pilter threads and symbols to remove extraneous information and focus on your own code during a debugging
session. The debug navigator sports two controls for filtering extraneous threads and program symbols: the
thread filter and the call stack slider.
7e fiIter tbreads and symbeIs in tbe debug navigater . . .
1. Pause your application's execution or wait for your code to stop at a breakpoint.
2. Use the thread filter button to hide threads that are not relevant to debugging.
Debug eur App
Lxamine Threads, Stacks, variables, and Memory
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
202
3. Use the call stack slider to ad|ust the amount of detail shown for each thread.
The thread filter button shows or hides threads that may not be relevant to debugging your code right
now. Lxamples of such threads include the heartbeat and dispatch management threads and any threads
that are idle and not currently executing any specific application code. Hiding these threads allows you to
focus on the threads that are doing actual work for your application.
Debug eur App
Lxamine Threads, Stacks, variables, and Memory
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
203
Por each thread, the call stack slider dynamically collapses or expands the list of symbols displayed by that
thread. Collapsing the list helps you focus your debugging efforts by hiding calls that are far removed from
your code. (The presence of hidden symbols is indicated by a dotted line in the stack frame.) Lxpanding
the list lets you see the precise set of calls that occurred to reach the current stopping point.
The screenshots show the debug navigator in two states. The screenshot on the left shows the debug
navigator with the thread filter turned off and the call stack slider set to showall stack frames. The screenshot
on the right shows it with the thread filter turned on and the call stack slider set to show only the most
relevant stack frames.
Nete: Piltering applies only to threads and their contents and does not apply to viewed memory
locations.
7e view memery Iecatiens . . .
1. |n the debug area, Control-click the variable whose memory you want to view.
2. Choose view Memory of "vot|oole from the shortcut menu.
Debug eur App
Lxamine Threads, Stacks, variables, and Memory
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
204
3. Use the debug navigator to select from among the viewed memory locations.
view memory locations to examine the raw contents of program variables. when you view a new memory
location from the debug area, an entry is added to the debug navigator and selected. The contents of the
selected memory entry are then displayed in the memory browser in editor pane.
The bottom of the memory browser contains controls you use to navigate the memory and customize its
display:
!
Address. Specifies the beginning address of the memory displayed in the memory browser.
!
Memery Page. Moves back or forward a memory page.
!
Number ef 8ytes. Specifies the number bytes in a memory page.
!
8yte Creuping. Specifies the size of the memory chunks displayed.
Memory locations are valid only while the application is running in the current debugging session. when
you quit the application, Xcode removes all memory entries from the debug navigator and discards them.
To remove a memory entry while you are still debugging, select the entry and press Delete.
Debug eur App
Lxamine Threads, Stacks, variables, and Memory
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
205
|nspect the value of a variable in a datatip to uncover a problem in the source code.
7e view variabIe vaIues in tbe seurce editer . . .
1. Place a breakpoint in the method you want to investigate.
2. Pun the pro|ect.
3. when execution stops, place the pointer on a variable that comes before the breakpoint.
4. |n the datatip that appears, inspect the current value of the variable.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
ou can also view the values of variables in the variables pane of the debug area.
The video illustrates inspecting the value of an integer variable in the method w1hdow01dLoad.
Capture OpenCL LS Prames
The debugging features for iOS OpenCL LS applications includes a facility for capturing and analyzing frames.
when frame capture is enabled in the scheme for the application, the debug bar provides a control for entering
the OpenCL LS frame debugging view.
Debug eur App
Capture OpenCL LS Prames
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
206
To enable this feature, you must run the application on a device and the device must be running iOS 5.0 or
later. Set the destination in the scheme menu to an iOS device and choose Ldit Scheme from the scheme
selector in the toolbar. Select the Pun action, click the Options tab, and select the OpenCL LS Lnable Prame
Capture checkbox (Pigure 7-6).
Iigure 7-6 Lnabling OpenCL LS frame debugging
Debug eur App
Capture OpenCL LS Prames
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
207
when you build and run your OpenCL LS application, the debug bar includes a frame capture button (Pigure
7-7). Click that button to capture a frame.
Iigure 7-7 Prame capture button
ou can use OpenCL frame capture to:
!
|nspect OpenCL LS state information.
!
|ntrospect OpenCL LS ob|ects such as view textures and shaders.
!
Step through draw calls and watch the changes with each call.
!
Step through the state calls that precede each draw call to see exactly how the image is constructed.
Debug eur App
Capture OpenCL LS Prames
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
208
Pigure 7-8 shows a captured frame. The debug navigator has a list of every draw call and state call associated
with that frame. The buffers associated with the frame are shown in the editor pane, and the state information
is shown in the debug pane.
Iigure 7-8 OpenCL LS frame capture
Debug eur App
Capture OpenCL LS Prames
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
209
ou can step through draw calls in the debug navigator, or by using the double arrows and slider in the debug
bar (Pigure 7-9).
Iigure 7-9 Controls for stepping through draw calls
Debug eur App
Capture OpenCL LS Prames
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
210
when you use the draw call arrows or slider, you can have Xcode select the stepped-to draw call in the debug
navigator. To do so, Control-click below the captured frame and choose Peveal in Debug Navigator from the
shortcut menu (Pigure 7-10).
Iigure 7-10 Shortcut menu
Debug eur App
Capture OpenCL LS Prames
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
211
ou can also use the shortcut menu to toggle between a standard view of the drawing and a wireframe view
(Pigure 7-11). The wireframe view highlights the element being drawn by the selected draw call.
Iigure 7-11 wireframe view
Debug eur App
Capture OpenCL LS Prames
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
212
Open the Assistant editor to see the ob|ects associated with the captured frame. |n the Assistant editor you
can choose to see all the ob|ects, only bound ob|ects, or the stack. Open a second Assistant editor pane to see
both the ob|ects and the stack for the frame at the same time (Pigure 7-12).
Iigure 7-12 Prame capture with two Assistant panes
Debug eur App
Capture OpenCL LS Prames
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
213
Double-click an ob|ect in the Assistant editor to see details about that ob|ect. Por example, if you double-click
a texture ob|ect, you can see the texture in detail. Pigure 7-13 shows the data in a vertex array (vAO) ob|ect.
Iigure 7-13 vertex Array Ob|ect detail
Debug eur App
Capture OpenCL LS Prames
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
214
Xcode enables you to replace text strings throughout your pro|ect and to perform refactoring operations. A
refactoring operationsuch as creating accessor methods for a symbol or creating a superclass from a
classchanges code without changing its behavior.
Peplace Text Strings
ou can use the search navigator to replace text strings throughout your pro|ect or workspace (Pigure 8-1).
(To make syntax-aware changes to symbol names, including within nib files, use the Pename refactoring
operation instead.)
Iigure 8-1 Search and replace using the search navigator
The search and replace operation can be customizedfor example, to limit the scope of the search or to match
the case of letters in the stringand provides a preview that you can use to accept or re|ect individual
replacements.
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
215
Make Pro|ectwide Changes
Nete: The first time you performa mass-editing operation such as search and replace, Xcode displays
a dialog giving you the option of first enabling automatic snapshots. ou can change this setting
any time in the Snapshots pane of the Pile > Pro|ect Settings or Pile > workspace Settings dialog.
ou can use a snapshot to back out all of your changes at once if necessary.
|f you don't have automatic snapshots enabled, you can make a manual snapshot of your pro|ect
before performing the operation by choosing Pile > Create Snapshot.
Peplace All |nstances of a Text String
The Peplace command does pattern matching in text files and replaces instances of the search string with the
replacement text you specify.
7e find and repIace text in yeur preject
1. Click the Pind pop-up menu in the search navigator and choose Peplace.
2. Type the text you want to find in the top text field and press Peturn.
Make Prejectwide Cbanges
Peplace Text Strings
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
216
Nete: Xcode does not search for the text until you press Peturn while the cursor is in the search
field. The Preview and Peplace buttons are not active until after you've performed the search
and one or more results are returned.
The Activity viewer in the workspace toolbar indicates when the find operation is in progress.
3. Type the replacement text in the lower text field.
4. Click Peplace All to replace every occurrence of the Pind text with the Peplace text. To replace a single
result, click that result to select it and click Peplace. To replace a subset of the occurrences found, use
Shift-click or Command-click to make your selection and click Peplace.
Make Prejectwide Cbanges
Peplace Text Strings
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
217
To see a previewof the changes before proceeding, followthe procedure in "Peplace Selected |nstances
of a Text String" (page 218).
Peplace Selected |nstances of a Text String
See what your changes will look like in your source code before deciding which occurrences to replace by
using the search navigator's preview feature.
7e preview cbanges befere repIacing text
1. Click the Preview button below the Peplace text field.
The preview dialog appears, showing the current version of each potential replacement in the right
column and the new version in the left column. Lach arrow points at the version being used. All the
potential replacements are selected by default.
2. To change the status (from selected to deselected, or vice versa) of one or more replacements, do one
of the following:
!
Click the checkbox for that change in the left pane of the dialog. Click the checkbox next to a
filename to change all the items in that file.
!
Click the button in the center of the right pane for each item whose status you want to change.
Make Prejectwide Cbanges
Peplace Text Strings
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
218
!
Use Shift-click or Command-click to select items in the list in the left pane, then press the Space
bar to change their status.
3. Click Peplace to carry out the replacement of the selected items.
Customize the Search
The search navigator provides Pind options to customize a search. Por example, you can specify its scope and
whether the search should be case sensitive.
7e specify a new scepe fer a searcb
1. |n the search navigator, click the magnifying glass in the search field to open the Pind options.
2. Open the "Pind in pop-up menu.
The default scope is the workspace. |f you have more than one pro|ect in the workspace, your pro|ects
are listed.
3. Choose Custom to create your own custom scopes.
Make Prejectwide Cbanges
Peplace Text Strings
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
219
4. |n the Pind Scopes dialog, click the Add (+) button to add a new custom scope.
5. Use the pop-up menus to specify the scope.
Depending on your choices, you might also have to fill in or select a value for a third scope parameter.
6. Select the name of the scope and type a new name for the scope to appear in the "Pind in menu.
ou can reopen this dialog and change the name at any time.
7. Pepeat this procedure as many times as necessary to define all the custom scopes you want to use.
Click Done when you're finished.
Make Prejectwide Cbanges
Peplace Text Strings
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
220
8. To see your custom scopes, open the "Pind in pop-up menu.
|mprove our Code's Structure Through Pefactoring
A refactoring operation improves the structure of source code without changing its behavior. ou refactor to
make the code easier to maintain, or as a first step in making further changes to the code.
Nete: Pefactoring works only with C and Ob|ective-C files.
Select the Source Code to Pefactor
8efore you can choose a refactoring operation (also called a ttonslotmot|on) from the Pefactor submenu in
the Ldit menu or from the shortcut menu in the source editor, you have to select the symbol or source code
that you want to refactor. Only the refactoring operations appropriate for the selected text are available in the
menu. The descriptions of the refactoring operations at the end of this chapter specify what code to select for
each type of refactoring operation.
when you select the code and the refactoring operation, Xcode presents a dialog to let you select options and
specify symbol names where necessary.
Make Prejectwide Cbanges
|mprove our Code's Structure Through Pefactoring
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
221
Preview the Changes 8efore Lxecuting the Operation
ou have the opportunity to previewthe changes and decide which files to include before applying the changes
by using the refactor preview dialog (Pigure 8-2).
Iigure 8-2 The refactor preview dialog
Deselect a file in the leftmost pane of the preview dialog to leave it out of the refactoring operation.
ou can edit your source code directly in the preview dialog. Any such edits are shown in the preview and
included in the refactoring operation.
8efore you've saved your updated files, you can use the Undo command in the Ldit menu on a per-file basis
to back out changes.
Impertant: 8y default, your changes are saved automatically when you close or build the pro|ect. To change
this behavior, open the Ceneral pane of Xcode preferences and set the Auto-save option to Ask or Never
Save.
Pun Unit Tests 8efore and After Pefactoring
As part of your refactoring workflow, you should develop unit tests for code you plan to refactor. Pun these
tests before and after a refactoring to verify that the refactoring operation doesn't change the behavior of the
modified code. Por more information on unit tests, see "Pun Unit Tests to Pind Pegressions" (page !).
Make Prejectwide Cbanges
|mprove our Code's Structure Through Pefactoring
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
222
Choose a Pefactoring Operation
The refactoring operations provided by Xcode include renaming a symbol, extracting a function or method
from other code, encapsulating accessors for a symbol, creating a superclass of a class, moving an item up into
a superclass, and moving an item down into one or more subclasses.
The Rename refactoring operation changes the name of the selected item throughout your pro|ect files.
7e cbange tbe name ef an item tbreugbeut yeur preject
!
Select any symbol except the declaration of a method inside a protocol interface, and choose Pename
from the Pefactor submenu in the Ldit menu (or from the shortcut menu in the source editor). (ou
con rename such a method if the selection is a definition of such a method in a class that adopts the
protocol. That is, if the container of the selection is a protocol, you cannot rename it, if the container
of the selection is a class, you can.)
The Pename refactoring operation differs from the Pind and Peplace command in that Pename is
symbol- and context-aware. Pind only matches strings. Pename is particularly useful with properties.
|f you're renaming a class and you have files that use that class in the filename, select the "Pename
related files option to rename the files as part of the refactoring operation.
The xtract refactoring operation creates a function or method from selected code.
7e extract a functien er metbed
1. Select code or code and comments within a function or method implementation, and choose Lxtract
from the Pefactor submenu in the Ldit menu (or from the shortcut menu in the source editor).
Xcode analyzes the context of the selected code and the variables it uses to determine the generated
routine's parameters and return value.
2. |n the dialog that appears, name the newroutine and its parameters, and select whether it is a method
or function.
The ncapsuIate refactoring operation creates accessors ("get and "set methods) for a symbol and changes
code that directly accesses the item to use the accessor methods instead.
7e create accessers fer a symbeI
!
Select a symbol that is an instance variable (1vaJ) or a member of a structure, and choose Lncapsulate
from the Pefactor submenu in the Ldit menu (or from the shortcut menu in the source editor).
The Create SupercIass refactoring operation creates a superclass from a class.
Make Prejectwide Cbanges
Choose a Pefactoring Operation
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
223
7e create a supercIass
1. Select a symbol that is a class defined in your pro|ect, and choose Create Superclass from the Pefactor
submenu in the Ldit menu (or from the shortcut menu in the source editor).
The Create Superclass refactoring operation creates skeletal interface and implementation statements
for a superclass placed in the inheritance hierarchy between the selected class and its existing superclass.
2. |n the dialog that appears, name the new superclass and select whether to create new header and
implementation files for its interface and implementation statements or put them in the existing file.
The Meve Up refactoring operation moves the declaration and definition of an item into the superclass of the
class where they currently reside, removing them from their former location.
7e meve tbe decIaratien and definitien ef an item inte a supercIass
1. Select a symbol that is a method or instance variable in a class, not a category, where the class and
superclass are defined in your pro|ect, and choose Move Up from the Pefactor submenu in the Ldit
menu (or from the shortcut menu in the source editor).
2. |n the dialog that appears, select whether also to move methods that directly access the refactoring
item and that are defined in the same class as the refactoring item.
The Meve Dewn refactoring operation moves the declaration and definition of the refactoring item to one or
more of the subclasses of the class that declares and defines the item.
7e meve tbe decIaratien and definitien ef an item inte ene er mere subcIasses
1. Select a symbol that is an instance variable in a class, not a category, where the class is defined in your
pro|ect and one or more subclasses already exist, and choose Move Down from the Pefactor submenu
in the Ldit menu (or from the shortcut menu in the source editor).
The Move Down refactoring operation moves the declaration and definition of the selected variable
into a subclass of the class where it currently resides, removing it from its former location.
2. |n the dialog that appears, specify the subclass into which to move the variable declaration and
definition.
Make Prejectwide Cbanges
Choose a Pefactoring Operation
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
224
ou manage iOS devices in Xcode using the Devices pane of the Organizer window (Pigure 9-1).
Iigure 9-1 Devices organizer
Although you can do much of your debugging and testing of an iOS application using iOS Simulator, simulation
cannot completely match the results of running your application on the target devices, you must test your
application on actual devices to ensure that it runs as intended and to tune it for performance on actual
hardware.
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
225
Manage our Devices
Nete: 8efore you can run your application on a device, you must first become a member of the iOS
Developer Program. See http://developer.apple.com/programs/ios to learn howto become a member.
Set Up our Device
To use a device with Xcode, you must provide the device with a provisioning profile and install iOS on the
device.
Provision a Device
|f you are a team administrator, or if your team administrator has already configured the necessary credentials
for you and your device, you can use the devices organizer to automatically download and apply the provisioning
profile.
Provision your iOS device to run generic apps on your device, such as sample apps.
7e previsien a device autematicaIIy fer deveIepment . . .
1. Open the Devices organizer.
2. Connect your device to your Mac.
Manage eur Devices
Set Up our Device
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
226
3. Select the device, and click "Use for Development.
Developing apps requires a provisioned device. The provisioning process sets up the required certificates
and configuration data that Xcode needs to install your apps on your device. when you provision a device
for generic development, Xcode adds your device to the generic teamprovisioning profile. This provisioning
profile allows development of most (but not all) types of apps. Por some types of apps (such as those that
use push notifications or in-app purchases), you must use a manually configured provisioning profile.
Some types of applications require manual provisioning. |n such cases, your team administrator must first
configure the necessary credentials for you, using the iOS Provisioning Portal. Pollow your administrator's
instructions to download the appropriate provisioning profile, and then use the devices organizer to locate
the provisioning profile on your file system and apply it.
Provision your device manually when you develop an app that requires a specialized provisioning profile.
Manage eur Devices
Set Up our Device
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
227
7e previsien a device manuaIIy fer deveIepment . . .
1. |n the Devices organizer, select Provisioning Profiles in the Library section.
2. Click Pefresh.
3. |dentify the specialized provisioning profile you need to use.
4. Drag the provisioning profile to the Provisioning Profiles group of the target device.
Apps that support push notifications or in-app purchases cannot use the generic teamprovisioning profile.
|nstead, those types of apps must use a specialized provisioning profile, which you create in the iOS
Provisioning Portal.
Manage eur Devices
Set Up our Device
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
228
Impertant: 8efore you can install a specialized provisioning profile on your device, that provisioning
profile must:
!
|nclude your development certificate
!
|dentify your device
Nete: All of the credentialing and provisioning procedures can be performed using the iOS
Provisioning Portal, a restricted-access area of the iOS Dev Center that stores information about your
development devices. Por details, see !ools wotlllow Cu|Je lot |O5.
Pestore or |nstall a version of iOS on a Device
ou should test your iOS application on devices running the version of iOS version targeted by the SDK you're
using. The devices organizer enables you to restore a currently installed version of iOS or to install a new
version.
|nstall a new version of iOS when you want to upgrade a device for development.
7e restere er instaII iDS en yeur deveIepment device . . .
1. Select the device you want to update from the Devices organizer.
2. Select an iOS version from the Software version pop-up menu.
3. Click the Pestore button, and confirm you want to install the software.
4. when installation is complete, activate the device and restore its contents using iTunes.
5. 8ack in Xcode, click "Use for Development in the Devices organizer to reenable development for the
device.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
ou may need to install iOS on your development device to run your app on a beta or CM version of the
iOS software.
Manage eur Devices
Set Up our Device
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
229
The Software version pop-up menu displays the versions of iOS that are available for you to install. |f the
version you want is not listed, you must add it to this menu before you can install it. To add the newsoftware
version to the menu, select Other version and navigate to the software image on your computer. Xcode
then adds the version to the pop-up menu and makes it available for installation.
when you enable a device for development, Xcode installs any provisioning profiles and development-related
data associated with the device. Xcode asks you for your developer program credentials and provisions
any new devices automatically before making them available for development.
Impertant: The version of iOS you install must be the same as or newer than the version currently
installed on the device. Attempting to install an older software image will fail. After a failed installation
attempt, you must reinstall the last successfully installed version or a newer version of iOS.
Nete: ou can download seed releases of the iOS SDK and iOS, when they are available, from the
iOS Dev Center.
Pun our Application On the Device
Set the run destination to iOS device in the scheme editor and build and run your application. Xcode transfers
the application to the device and executes it.
Pemove an Application from a Device
Successful development and testing frequently depend on starting with a clean execution environment. To
achieve this state, you can completely remove your application from a device.
Delete an app from your device to remove all data files associated with the app.
7e remeve yeur appIicatien frem a device . . .
1. |n the Devices organizer, select Applications in the device.
2. Select an app from the list of installed apps.
Manage eur Devices
Pun our Application On the Device
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
230
3. Click Delete, and confirm that you want to remove the app.
During development, you might remove an app in order to test code that runs only when your app is first
launched.
PromXcode, you can remove only the apps that you created. ou cannot remove any of the system-installed
or third-party apps from the device using Xcode.
Manage eur Devices
Pun our Application On the Device
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
231
AIternative: Another way to remove a third-party app (including your own) from a device is to
touch and hold the app icon on the device until the icons start wiggling. Then tap the close box
on a given app to remove it from the device. when you are done, press the Home button.
Download our Application's Data for Analysis
ou probably have favorite tools that you use in inspecting application-generated data. To use such tools, you
need to copy that data to your computer intact. To do so, you download the data from the devices organizer,
specifying a location for the data on your local file system.
Copy an app's data from its sandbox on an iOS device to your file system to examine or modify the data.
7e dewnIead yeur appIicatien's data frem a device . . .
1. |n the Devices organizer, select Applications in the device.
2. Select the app.
3. Click Download.
Manage eur Devices
Pun our Application On the Device
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
232
4. Specify the name and location of the app-data package.
Manage eur Devices
Pun our Application On the Device
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
233
when you copy the app data, the app itself is not copied, and neither is any data the app stores in the
keychain.
Analyzing the contents of an app's sandbox may provide important information to help you diagnose
problems or tune the app. ou can examine files that the app createdor that it obtained froman external
sourceto find out whether the files contain valid information or indicate a problem.
Capture and Use Screenshots from a Device
Screenshots are important in several aspects of development and distributionfor example, serving as
illustrations in documentation and as graphics for the App Store and other marketing needs.
|n the organizer you can capture and manipulate screenshots of your application running on the device.
Capture a screenshot on your device to document your progress during development, and create launch
images for your iOS apps.
7e capture screensbets frem a device . . .
1. On the device, configure the screen the way you want it.
2. |n the Devices organizer, select Screenshots in the device.
Manage eur Devices
Capture and Use Screenshots from a Device
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
234
3. Click New Screenshot.
when generating your app's default images, you should always capture images from devices with the
appropriate screen size and resolution. Por a universal app, this means capturing screenshots both from
an iPad and froman iPhone or iPod touch. Por an app that also supports Petina displays, it means capturing
screenshots from an iPhone 4 in addition to any other devices.
Set a Screenshot as our iOS Application's Launch |mage
An application launch image, or Jeloult |moe , enhances the user's experience at application launch. when
the user starts your application, iOS immediately displays this image. our application then displays its first
screen as soon as possible, replacing the launch image.
Set the launch image of your app to give the user immediate feedback that the app launched.
Manage eur Devices
Capture and Use Screenshots from a Device
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
235
7e set a screensbet as yeur iDS appIicatien's defauIt image . . .
1. |n the Devices organizer, select Screenshots for a device or for the Library section.
2. Select an image.
3. Click "Save as Launch |mage.
4. Specify the name of the image and the target app, and click Next.
A launch image acts as a placeholder for your app's user interface at launch time. when the user launches
your app, the iOS presents this image until your app displays its main window and starts responding to
events.
An iPhone app has only one launch image, typically named 0e1au11.phg. An iPad app can have multiple
launch images, each one presenting the app's user interface in a specific device orientation. Launch images
may have names other than 0e1au11.phg.
Manage eur Devices
Capture and Use Screenshots from a Device
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
236
To help avoid a |arring experience when this switch occurs, the ideal default image looks identical to the first
screen your application displays, except that it should omit any U| elements that could change.
Lxport a Screenshot to our Pile System
To use a screenshot outside your application, for example, in documentation or marketing materials, you can
export it from within the devices organizer.
Save a screenshot to your file system to archive it or use it for materials related to your app.
7e expert a screensbet te yeur fiIe system . . .
1. |n the Devices organizer, select the appropriate Screenshots group.
2. Select the screenshot, and click Lxport.
3. when prompted, enter a name and location for the screenshot, and click Save.
Manage eur Devices
Capture and Use Screenshots from a Device
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
237
ou may want to provide one or more screenshots of your app when submitting it for publication on the
App Store.
Saved screenshots are exported as high-quality PNC files.
with the screenshot file on your computer file system, you can modify it with any graphics editing application
that accepts PNC files.
|dentify Small U| Changes by Comparing Screenshots
As development progresses, small changes you have made to your U| may be unrecorded and remain unnoticed
until late in the development cycle. To help mitigate this problem, you can compare different versions of a
screenshot to determine exactly what has changed.
Compare screenshots to detect subtle changes to your user interface.
7e cempare screensbets . . .
1. |n the Devices organizer, select the appropriate Screenshots group.
2. Select two or more screenshots.
3. Select the Compare option.
Manage eur Devices
Capture and Use Screenshots from a Device
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
238
4. Use the Tolerance slider to ad|ust the comparison threshold.
The screenshots you select must be the same size and at least somewhat similar. ou cannot compare
screenshots whose resolution or dimensions are different. Por example, you cannot compare a screenshot
taken on a Petina display with one taken on a lower-resolution display. |f the content of the screenshots is
completely different, the Compare option is not available.
Transfer our Developer Profile to Another Computer
our developer profile is your official digital identification for iOS application development. |f your development
workflow requires you to use another user account or another computer, you must copy that profile to that
other account or computer.
Manage eur Devices
Transfer our Developer Profile to Another Computer
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
239
To do so, you first export your profile, which archives the profile into a password-protected secure file in a
location that you specify on your operating system. This export is performed in the devices organizer.
Archive your code signing assets to keep them safe or to use them on another Mac.
7e expert yeur deveIeper prefiIe . . .
1. |n the Devices organizer, select your team in the Teams section.
2. Click Lxport.
3. Specify a filename and a password, and click Save.
Manage eur Devices
Transfer our Developer Profile to Another Computer
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
240
The file produced contains the items you need to code sign apps, including the provisioning profiles,
certificates, and private keys needed to install apps in development on a device.
8ecause it contains sensitive information that can be used to sign apps in your name, the contents of the
file are stored in an encrypted format using the password you provide. That password is required later to
import the file to another system.
Next, you copy the archive file to the other account or computer.
Pinally, in the other account or on the other computer, you use the devices organizer to import your profile
by extracting it from the archive file.
Place your code signing assets on a new Mac by importing the code signing assets exported from another
Mac.
7e impert yeur deveIeper prefiIe . . .
1. |n the Devices organizer, select your team in the Teams section.
2. Click |mport.
3. Select the file containing your code signing assets.
Manage eur Devices
Transfer our Developer Profile to Another Computer
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
241
4. Lnter the password for the file, and click Open.
The importation process installs the certificates, private keys, and provisioning profiles that are stored in
the developer-profile file.
7reubIesbeeting: |f you don't see the Team section in the devices organizer:
!
Drag the password-protected file that contains your code signing assets to the Xcode icon
in the Dock.
Manage eur Devices
Transfer our Developer Profile to Another Computer
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
242
Pinally, in the other account or on the other computer, you use the devices organizer to import your profile
by extracting it from the archive file.
Manage eur Devices
Transfer our Developer Profile to Another Computer
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
243
As you create your app, Xcode automatically saves changes to source, pro|ect, and workspace files. This feature
simplifies workflow, helps keep you from losing any of your work, and requires no configuration.
when creating an app, sometimes you may want to experiment with a new user interface layout and then
revert to the previous one. Or you may need to undo some code that you've |ust written because you found
an error or problem. These circumstances require that you understand how Xcode saves your work to disk and
know how to revert your work to a prior state.
This chapter explains how Xcode automatically saves your work and shows how to use the Pevert Document
and Undo commands. The Snapshot feature is introduced as well as Xcode's built-in interface to source code
management so that you understand how they relate to the overall tasks of change management in your
development pro|ects.
Save when Lditing
As you edit, Xcode continuously tracks changes and saves them, but it does not continuously write the changes
to disk. They are saved in memory as you work. Xcode then automatically writes your changes to disk when
one of five operations is performed:
!
ou build and run your app.
!
A snapshot is created.
!
ou commit files to an SCM repository.
!
ou close the pro|ect.
!
ou quit Xcode
ou can also save changes to disk manually using the Save command in the Pile menu.
Pevert to the Last Saved version
To discard all changes you've made to a file since it was last saved, use the Pevert Document command in the
Pile menu. After a confirmation dialog appears, click the Pevert button to complete the operation.
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
244
Save and Pevert Changes to Piles
The Pevert Document command is available only when the contents of a file have been changed since it was
last saved to disk. Piles with in-memory changes are indicated in two places: The file icon is highlighted in the
pro|ect navigator and in the associated editor pane's |ump bar. Highlighted icons in the pro|ect navigator let
you see which files have in-memory changes throughout the entire pro|ect. The highlighted icon in an editor's
|ump bar indicates whether any changes to the document currently in view were made since it was last saved.
Por example, in Pigure 10-1 you see a workspace window with the file ^a1h^ehu.x1b open in the primary
editor and three text files (Coh1Jo11eJ.h, Coh1Jo11eJ.m, and Read^e.1x1) open in assistant editors.
Iigure 10-1 workspace window with in-memory changes to files
Open with changes
Three of the four files open in Pigure 10-1 have changed since they were last saved, indicated by the highlighted
icons in the |ump bars and in the pro|ect navigator. The Pevert Document command allows you to revert to
the last saved version of each file, one at a time. |t acts on the file that currently has the editing focus, obtained
by clicking in its editor pane or by clicking its name in the pro|ect navigator. |n this illustration, ^a1h^ehu.x1b
has the editing focus, which you can tell by the slightly darker coloring of the |ump bar in the primary editor.
Using Pevert Document in Xcode always returns the contents of the file to the last saved version on disk. |f
you are not sure when the file was last saved to disk relative to when you made changes, or you would prefer
to back out changes one at a time, use the Undo command in the Ldit menu.
Save and Revert Cbanges te IiIes
Pevert to the Last Saved version
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
245
Undo Changes |ncrementally
To back out changes to a file incrementally, use the Undo command in the Ldit menu, shown in Pigure 10-2.
Iigure 10-2 Undo Typing command
Nete: The Undo command is context sensitive to the last editing operation performed. Por example,
the command changes from Undo to Undo Typing or to Undo Add Menu |tem depending on the
context of the last operation performed.
After you've chosen the Undo command, the Pedo command becomes available to reverse the last
undo operation.
The Undo command in Xcode allows you to incrementally back out all changes to a file since the start of an
editing session. An editing session begins when you open a pro|ect with Xcode and ends when you close the
pro|ect. when you work on a file in a single session, Xcode lets you undo all the edits in that session, even
those already saved to disk.
when you work in a text document and choose Undo, the source editor sets the insertion point to the affected
section of the text and brings that section into view. |n this way, you knowthe change that the Undo command
has undone.
Save and Revert Cbanges te IiIes
Undo Changes |ncrementally
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
246
Nete: Using the Pevert Document command clears the Undo history, you cannot undo a revert
operation.
Unlocking Piles
Piles included in a pro|ect may be locked for several reasons. Por example, they may be header files included
in system frameworks, or they may have been intentionally locked in the Pinder to prevent accidental deletion
and renaming. Locked files cannot be edited, they are available only for reading, searching, and selecting
portions to copy.
|f you attempt to edit the contents of a locked file, Xcode presents a notification asking whether you want to
unlock the file. Click the Unlock button to continue the unlocking operation. |f the file cannot be unlocked,
you receive another notification (see, for example, Pigure 10-3).
Iigure 10-3 Pile could not be unlocked
Save and Revert Cbanges te IiIes
Unlocking Piles
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
247
Locked files are indicated in the Xcode workspace by a locked file icon in the pro|ect navigator or by a lock
icon in the associated editor pane's |ump bar. The locked file icon also appears in the workspace window title
when the document is in the primary editor pane (see Pigure 10-4).
Iigure 10-4 Locked file indicators
Locked file icon Locked file icon Lock icon
Nete: The locked file icon appears in the pro|ect navigator only for files that are locked in the Pinder.
Piles locked for write access due to ownership permissions or read-only media show the lock icon
in the |ump bar.
when you start editing a locked file, Xcode asks whether you want to unlock it. ou can also unlock a file by
using the Unlock command in the Pile menu or by clicking on the lock icon in the |ump bar of its associated
editor pane.
Save and Revert Cbanges te IiIes
Unlocking Piles
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
248
Use Snapshots and SCM for Pro|ectwide Change
when you develop a pro|ect, you often make changes on a larger scale than changes to individual files. The
snapshot and source code management systems provide save and revert facilities that operate pro|ect wide.
Snapshots Archive Pro|ectwide Changes to Documents and Configuration
Use the Create Snapshot command in the Pile menu to create an archive of the pro|ect or workspace.
ou can make three types of pro|ectwide changes for which the Pevert Document and Undo commands are
not supported:
!
Xcode pro|ectwide operations, which involve changes to many document files and potentially to pro|ect
settings. These operations include refactoring code, adding Automatic Peference Counting to an existing
pro|ect, and performing pro|ect validation.
!
Ad|ustments to the workspace and pro|ect settings. Xcode saves these changes to disk as they are performed
by modifying the .xcodepJo and .xcwoJkspace files.
!
our global editing operations using search and replace functions.
Snapshots are archives that include the current state of all pro|ect and workspace settings and all document
files included in the pro|ect context. All document files are saved when a snapshot is created. Xcode always
stores snapshots in your local file system.
Creating a snapshot before making changes to pro|ect settings, and before using global search and replace,
gives you the ability to revert the entire pro|ect to the state it was in before you performed a pro|ectwide
operation.
Nete: Xcode automatically creates a snapshot of the pro|ect before performing refactoring, automatic
reference counting conversion, and validation.
Por more information about snapshots, see "Save and Pevert Changes to Pro|ects" (page 251).
SCM Pepositories Manage Overall Change as our Pro|ect Develops
The Source Control commands in the Pile menu allow you to manage your pro|ect files with a source code
management (SCM) repository.
Automatic save, revert, undo, and snapshots are intended to help the flow of editing and making ad|ustments
as you develop your pro|ect with respect to the document files it includes. These features are not intended to
be the way you manage overall pro|ect change through the development history of a pro|ect. To support this
Save and Revert Cbanges te IiIes
Use Snapshots and SCM for Pro|ectwide Change
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
249
larger scope of managing change in your development work, Xcode provides built-in access to source code
management commands that allow you to use both locally stored and server-based SCM repositories. Using
an SCM repository is strongly recommended even for small development pro|ects.
Por more information about using source code management, see "Save and Pevert Changes to Pro|ects" (page
251).
Save and Revert Cbanges te IiIes
Use Snapshots and SCM for Pro|ectwide Change
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
250
Xcode provides several ways to save versions of your pro|ect:
!
A snapshot saves the current state of your pro|ect or workspace on disk for possible restoration later.
!
Source control repositories keep track of individual changes to files and enable you to merge different
versions of a file.
!
An archive packages your products for distribution, either through your own distribution mechanism or
for submission to the App Store. See "To create a workspace" (page 62) for details.
Xcode provides direct support for Cit and Subversion repositories, including an option to create a local Cit
repository when you create a new pro|ect. 8ecause it's so easy to set up a repository to use with your Xcode
pro|ect, Xcode provides a special editor, called the vets|on eJ|tot , that also makes it easy to compare different
versions of files saved in repositories.
This chapter assumes that some developers using Xcode are new to repositories. |f you're an experienced
repository user, skip over the introductory material in each section and go straight to the descriptions of aspects
of Xcode's repository U|.
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
251
Save and Pevert Changes to Pro|ects
Take a Snapshot of our Pro|ect
A snapshot provides an easy way to back up the current version of your pro|ect or workspace so that, if
something goes wrong with a change or process, you can restore the earlier version. Xcode can create a
snapshot automatically before a ma|or change such as refactoring your code or executing a Pind and Peplace
operation. ou can change this setting any time in the Snapshots pane of the Pile > Pro|ect Settings or Pile >
workspace Settings dialog (Pigure 11-1).
Iigure 11-1 The Snapshots settings dialog
ou can also set Xcode to automatically create snapshots in other circumstances, such as before a build, by
selecting the Create Snapshot option in the 8ehaviors pane of Xcode preferences ("Customize our 8uild and
Pun workflow" (page !)).
ou can create a snapshot manually whenever you like by choosing Pile > Create Snapshot. To see where
Xcode stores your snapshots, or to change the location, look in the Locations pane of Xcode preferences or
the Snapshots pane of the Pro|ect (or workspace) Settings dialog.
Impertant: To use snapshots, you must have selected System Tools in the Xcode installer. This option is
selected by default.
To see the snapshots for a pro|ect or workspace, click the pro|ect in the pro|ects organizer. To restore from a
snapshot in Xcode 4.0, select a snapshot in the pro|ects organizer and click the Pestore Snapshot button at
the bottom of the window.
|n Xcode 4.1 and later, to restore a snapshot, choose Pestore Snapshot from the Pile menu and select the
snapshot to restore. Xcode displays a preview dialog in which you can review the differences between the
current version of the pro|ect and the snapshot version. when you click Pestore, Xcode replaces the current
version of the pro|ect with the version in the snapshot. Xcode makes a snapshot of the current version before
replacing it.
Save and Revert Cbanges te Prejects
Take a Snapshot of our Pro|ect
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
252
To restore a snapshot in a new location instead of restoring on top of the current pro|ect, select the pro|ect in
the Pro|ects pane of the Organizer window, choose the snapshot you want to restore, and click the Lxport
Snapshot button at the bottom of the window (Pigure 11-2).
Iigure 11-2 Snapshots listed in the Organizer window
8ecause Xcode 4 keeps track of all your pro|ects and displays them in the pro|ects organizer even if they no
longer exist, you can restore a deleted pro|ect from a snapshot.
Keep Track of Changes with Source Control
when working on a software pro|ect, it can be very useful to use software control management (SCM) to keep
track of changes in the code and coordinate work groups. An SCM system, also referred to as soutce conttol ,
saves multiple versions of each file on disk, storing metadata about each version of each file in a location known
as an 5CV teos|toty .
why Use Source Control!
There are two fundamental reasons for using source control:
Save and Revert Cbanges te Prejects
Keep Track of Changes with Source Control
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
253
!
A source control system helps you reconstruct past versions of the software and the process used to
develop it. |f you are working on a pro|ect by yourself, you can commit a file to your SCM repository each
time you make a ma|or change. Then, if you find you've introduced bugs, you can compare the newversion
with a past version that worked correctly to help to locate the source of the trouble. |n the worst-case
scenario, you can revert to an earlier version and start over from there to reimplement the new feature. |f
you keep your repository, or a copy of the repository, in another, physically safe location, you can even
reconstruct your pro|ect if your computer is lost or destroyed.
!
when two or more people are working on the same pro|ect, source control helps prevent conflicts and
helps resolve conflicts should they arise. 8y keeping a central repository that holds the canonical copy of
the software, the source control system allows each programmer to work on his or her own local copy
without any danger of corrupting the canonical version. |f you set up a systemof checking out a file before
working on it, you can ensure that two people are not working on the same code at the same time. |f two
people do change the same code, the SCM software helps you to merge the two versions. ou can also
look through past changes to see what they were and who made them, which can be a great help in
managing the pro|ect and in fixing bugs.
Choose Cit or Subversion
Xcode supports two SCMsystems: Subversion (often abbreviated svn) and Cit. Subversion is always server-based
and the server is normally on a remote machine, though it is possible to install one locally. Cit can be used
purely as a local repository, or you can install a Cit server on a remote machine to share files among team
members. The Xcode 4 installer installs the Cit and Subversion tools when you select System Tools.
|f you are working alone, it's generally easiest to use Cit, as you don't need to set up a server. |n fact, Xcode
can automatically set up a Cit repository for you when you create a new pro|ect (see "Create a Cit Pepository
Por our New Pro|ect" (page 58)). Por a group pro|ect, the choice of Subversion or Cit is usually a matter of
taste and prior experience.
|n so far as is possible, Xcode provides a consistent user interface and workflow for users of either Subversion
or Cit.
Learn SCM Terminology
|n general, you work on a copy of the pro|ect (called, appropriately, a wotl|n coy ). The command to create
a working copy is clone for Cit and cleclout for Subversion. when you have changed one or more files and
want to add your changes to the repository, you execute a comm|t command to the SCM software. The SCM
software records the date and time of the commit, any comments you include to help you remember later
why you committed this version of the code, your identity (that is, the identity of the person who executed
the commit command), and any other information the SCM software needs in order to keep track of the
software.
Save and Revert Cbanges te Prejects
Keep Track of Changes with Source Control
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
254
8ecause Subversion repositories always reside on a server, when you commit changes to your pro|ect, Xcode
sends those changes back to the server. 8ecause Cit repositories can be local or on a server, the situation is a
bit different with Cit. Por Cit, your working copy is also a local repository, so once you've committed the file,
the repository has been updated. Lven if you have a remote Cit server, committing a file in Cit does not
automatically send changes to the server. To update the Cit repository on a remote server, you use a usl
command.
To update your working copy with the latest version of the file in a remote repository, you use a ull command
(in Cit) or uJote command (in Subversion). Por a local Cit repository, the pull command is not needed.
The main line of code for development is often referred to as the ttunl . To avoid modifying the trunk while
developing newfeatures, you can create a newcopy of the pro|ect referred to as a otoncl. Lventually, branches
are merged back into the trunk. |n Cit, a branch is simply a working copy of the pro|ect. |n Subversion, a branch
is a copy maintained by the repository. ou can check out any number of working copies of a Subversion
branch. when you update your local working copy with the update or pull command, and when you merge
two branches or merge a branch into the trunk, Xcode displays a dialog that lets you reconcile differences
between the versions. ou can also use the version editor to compare two versions of a file at any time.
Save and Revert Cbanges te Prejects
Keep Track of Changes with Source Control
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
255
Manage our Pepositories
|n Xcode, you configure SCM repositories in the Organizer (Pigure 11-3).
Iigure 11-3 The repositories pane in the Organizer window
The repositories pane of the Organizer window (referred to hereafter as the teos|tot|es oton|zet ) lets you
examine the structure of the repository (folders, files, and branches) and your working copy. |n addition to the
more obvious features provided by the repositories organizer, it lets you assign address-book information to
the person who committed each version listed and you can examine the changes to each file for each commit.
7e assign address beek infermatien te identities in tbe erganizer
1. Click a repository in the navigation pane of the repositories organizer.
Save and Revert Cbanges te Prejects
Keep Track of Changes with Source Control
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
256
2. Click the icon well next to the commit |D number.
3. Pill in the information about the person who executed the commit, or if the person is in your address
book, click Choose Card and select that person's card in your address book. |f your address book has
a picture associated with the entry, the picture is displayed in the organizer.
Save and Revert Cbanges te Prejects
Keep Track of Changes with Source Control
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
257
view files in a specific commit version to inspect changes that you have made to those files.
7e view cbanges fer a specific cemmit versien . . .
1. |n the navigation pane of the repositories organizer, select the working copy folder of the pro|ect.
2. Click the disclosure triangle next to the commit |D number.
3. Click view Changes.
4. Select a file in the navigation pane.
5. Scroll, if necessary, to view changes in the file.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
Clicking the disclosure triangle for a commit version reveals a list of changed files, allowing you to quickly
scan for the one you want to inspect.
|n the inspection dialog, Xcode displays the changes between the file you have chosen and the previous
commit of the same file. Por convenience, each change is highlighted in the editor pane and indicated by
a red mark in the scroll bar.
The video shows viewing changes in the SKTL1he.h file in the most recent commit version of the
Skec1h_g11_^ repository.
Pind SCM Commands
SCM commands are located in the main Xcode menu, in the shortcut menu, and in the repositories organizer.
Save and Revert Cbanges te Prejects
Keep Track of Changes with Source Control
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
258
Source control commands are in the Source Control submenu of the Pile menu (Pigure 11-4).
Iigure 11-4 The Source Control submenu of the Pile menu
The pro|ect navigator shortcut menu contains a subset of these commands (Pigure 11-5).
Iigure 11-5 The Source Control submenu of the pro|ect navigator shortcut menu
Many SCM commands can be executed by using buttons at the bottom of the repositories organizer. which
buttons are available and active depends on your selection in the navigator pane of the repositories organizer.
Por example, Pigure 11-6 shows the buttons at the bottom of the repositories organizer when a git working
copy is selected.
Iigure 11-6 Pepositories organizer buttons
Update and commit operations are recorded in the log navigator. Select a log to see the individual steps of
that operation in the log viewer.
Save and Revert Cbanges te Prejects
Keep Track of Changes with Source Control
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
259
Keep Track of our Piles' SCM Status
ou can keep track of your files' SCM status in the pro|ect navigator. SCM status is shown as a badge next to
the file name (Pigure 11-7), as follows:
SCM status 8adge
Locally modified
^
Updated in repository
b
Locally added
A
Locally deleted
0
|gnored
T
Peplaced in the repository
R
The contents of the folder have mixed status, display the contents to see individual status
-
Not under source control
?
Iigure 11-7 Source control badges in the pro|ect navigator
8adges propagate up to the highest container so you can see the source control status of the whole workspace
regardless of the disclosure level. Detailed SCM status is shown in the Source Control area of the Pile inspector
in the utility pane.
Save and Revert Cbanges te Prejects
Keep Track of Changes with Source Control
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
260
work with Cit and Subversion
Common source control tasks include setting up a repository, checking files out of and in to a repository,
reconciling different versions of a file, and using branches to isolate risky changes to your code.
Set Up Cit version Control when ou Create a New Pro|ect
As described in "Create a Cit Pepository Por our New Pro|ect" (page 58), Xcode creates a Cit repository for a
newpro|ect if you select the Source Control option in the Save As dialog. when you do so, Xcode adds a hidden
file (named .g11) to the folder containing the pro|ect. That file contains all the information Cit needs to keep
track of the files in the pro|ect and the changes made to them. Xcode also performs an initial commit of the
files in the folder. Any time you add files to your pro|ect or modify any of the files in the pro|ect, you need to
commit them to add them to the repository (see "Commit Piles to Add Them to a Pepository" (page 271)).
Add Cit or Subversion version Control to an Lxisting Pro|ect
ou may need to create your own repository if, for example, you want to start managing an existing pro|ect
under source control. ou can use command-line tools to set up a Cit or Subversion repository. The necessary
tools are installed during Xcode installation, if you select the System Tools package.
Use command-line commands to set up a Cit repository for an existing pro|ect.
7e set up a Cit repesitery frem tbe cemmand Iine . . .
1. Use the cd command to switch to your pro|ect directory, making it the current working directory.
2. Lnter g11 1h11 to create an empty repository.
3. Lnter g11 add . to copy your pro|ect files into the repository.
4. Lnter g11 comm11 -m "Th111a1 comm11" to commit all the files.
// S1ep 1
$ cd /bseJs/me/samp1e_code/Ske1ch
// S1ep 2
$ g11 1h11
Th111a11zed emp1y C11 Jepos11oJy 1h /bseJs/me/samp1e_code/Ske1ch/.g11/
// S1ep 3
$ g11 add .
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
261
// S1ep 4
$ g11 comm11 -m "Th111a1 comm11"
[mas1eJ {Joo1-comm11) 173067e] Th111a1 comm11
...
74 111es chahged, 10198 1hseJ11ohs{+)
cJea1e mode 100644 .0S_S1oJe
cJea1e mode 100644 AJJow.1111
cJea1e mode 100644 C1Jc1e.1111
cJea1e mode 100644 CJoss.1111
cJea1e mode 100644 0Jaw2App.1chs
cJea1e mode 100644 0Jaw2F11e.1chs
cJea1e mode 100644 Ehg11sh.1pJo/0Jaw2.h1b/c1asses.h1b
...
cJea1e mode 100644
Ske1ch.xcodepJo/xcuseJda1a/eJhes1.xcuseJda1ad/xcdebuggeJ/BJeakpo1h1s.xcbkp111s1
cJea1e mode 100644
Ske1ch.xcodepJo/xcuseJda1a/eJhes1.xcuseJda1ad/xcschemes/Ske1ch.xcscheme
cJea1e mode 100644
Ske1ch.xcodepJo/xcuseJda1a/eJhes1.xcuseJda1ad/xcschemes/xcschememahagemeh1.p11s1
cJea1e mode 100644 Tex1CJaph1c.1111
To set up a repository for an existing pro|ect, you have to use the command-line shell implemented by the
Terminal utility app.
Use command-line commands to set up a Subversion repository.
7e set up a Subversien repesitery frem tbe cemmand Iine . . .
1. Use the mkd1J command to create a directory with three subdirectories named bJahches, 1ags, and
1Juhk to hold a temporary copy of your pro|ect.
2. Copy the pro|ect directory into the 1Juhk subdirectory.
3. Create a directory for the Subversion repository.
4. Use the svhadm1h cJea1e command to create an empty Subversion repository.
5. Use the svh 1mpoJ1 command to import your pro|ect directory into the new Subversion repository.
// S1ep 1
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
262
$ mkd1J /Ske1ch_svh_1mp
$ mkd1J /Ske1ch_svh_1mp/1Juhk
$ mkd1J /Ske1ch_svh_1mp/bJahches
$ mkd1J /Ske1ch_svh_1mp/1ags
// S1ep 2
$ cp -R /bseJs/me/samp1e_code/Ske1ch /Ske1ch_svh_1mp/1Juhk
// S1ep 3
$ mkd1J /svh_Jep
// S1ep 4
$ svhadm1h cJea1e /svh_Jep/Ske1ch_svh
// S1ep 5
$ svh 1mpoJ1 /Ske1ch_svh_1mp 111e:///svh_Jep/Ske1ch_svh -m "Th111a1 1mpoJ1"
Add1hg /Ske1ch_svh_1mp/1Juhk
Add1hg /Ske1ch_svh_1mp/1Juhk/Ske1ch
Add1hg /Ske1ch_svh_1mp/1Juhk/Ske1ch/SKTCJaph1cv1ew.h
Add1hg {b1h) /Ske1ch_svh_1mp/1Juhk/Ske1ch/CJoss.1111
Add1hg /Ske1ch_svh_1mp/1Juhk/Ske1ch/SKTApp0e1ega1e.h
...
Add1hg /Ske1ch_svh_1mp/1Juhk/Ske1ch/NSCo1oJ_SKTScJ1p11hg.m
Add1hg /Ske1ch_svh_1mp/bJahches
Add1hg /Ske1ch_svh_1mp/1ags
Comm111ed Jev1s1oh 1.
To set up a Subversion repository, you have to use the command-line shell implemented by the Terminal
utility app.
|f you don't have an existing pro|ect, use Xcode to create a pro|ect before setting up your repository.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
263
Nete: 8y convention, a Subversion repository contains three additional subdirectories named
bJahches, 1ags, and 1Juhk.
Clone or Check Out a Copy of a Pro|ect to Use Locally
|f you or your work group have a Subversion server or a master copy of a Cit repository shared on a file server,
you can create a local working copy by checking out (Subversion) or cloning (Cit) a copy of the master. ou
can then use the source control commands in Xcode to commit changes to your local copy, update your local
copy fromthe master copy, and push your changes up to the master copy (for Cit). Note that it is not necessary
to clone a copy of a local Cit repository, as in this case the master copy is also your working copy.
Check out or clone a repository to create a copy on your local system.
7e cbeck eut er cIene a repesitery . . .
1. |n the repositories organizer, click the Add button and choose Checkout or Clone Pepository.
2. Lnter the pathname or UPL for the file.
3. when the "Host is reachable indicator turns green, click the Next button.
4. Lnter a local name for the repository and click Clone (or Checkout) to copy it.
5. Choose a location and click the highlighted Clone (or Checkout) button to save the local repository.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
8y abstracting common repository operations, Xcode supports both Cit and Subversion (SvN) repositories
with a single, unified graphical user interface and workflow. Depending on your choice, this one operation
checks out (for SvN) or clones (for Cit) the repository and integrates it with your pro|ect.
Cloning a Cit repository in Xcode sets up a complete repository on your local system and integrates that
repository with your workspace so that you can quickly start using it. This approach gives you the benefits
of distributed version control, including full commit rights, whether you're online or not.
An SvN checkout operation does not create a local repository. ou must have a network connection to the
repository server to be able to commit changes.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
264
Por SvN, you must also provide the relative paths to the 1Juhk, bJahches, and 1ags directories. To do
so, click the name of the new repository in the repositories organizer and fill in the associated fields. |f your
SvN server requires authentication, fill in the user name and password as well.
The video shows cloning a Cit repository for the Sketch sample code pro|ect.
Add an Lxisting SCM working Copy of a Pro|ect to Xcode
|f you have a working copy of a pro|ect that was checked out of Subversion or cloned from Cit using the
command line or another tool, you can add it to your Xcode SCM repository support. To do so, click the Add
button (+) at the bottom of the navigation pane in the repository organizer and choose Add working Copy.
Create a 8ranch to |solate Pisky Changes
After you've been working on a pro|ect for a while, you are likely to have a body of reliable, stable code.
Although a repository enables you to revert to an earlier version if you destabilize your programwhile attempting
to add a new feature, you might want to be able to work on the new feature while still maintaining your stable
body of code. That way, one of the members of your teamcan (for example) work on refining the user interface
or fixing minor bugs while another team member works on a risky new feature. |n order to implement such a
scheme, most source control systems (including Cit and Subversion) allow you to create a branch, which is
another copy of your code that you can modify independently of the original body of code (or of any other
branches). ou can base a branch on the trunk or on any other branch.
Subversion keeps all the information about branches, submissions, updates, and so forth on the server. ou
need to be connected to the server to see any of this information in Xcode. |n Cit, when you clone a repository,
you get a copy of all of the metadata associated with the repository as well as copies of all the existing branches.
To see the structure of a Subversion repository without checking out a working copy, or to see the branches
of a remote Cit repository so you can clone an individual branch, use the Add Pepository menu item(see "Clone
a Specific 8ranch" (page 268)).
Create a branch in a repository to isolate specific aspects of your software development efforts and to work in
parallel with other developers.
7e create a brancb in a Cit repesitery . . .
1. |n the repositories organizer, select the appropriate 8ranches directory in the navigator pane and click
the Add 8ranch button.
2. Lnter a name for the new branch.
3. Prom the pop-up menu, choose an existing branch to serve as the starting point for this new branch.
4. |f appropriate, select the option to automatically switch to the new branch.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
265
5. Click Create.
Cit creates the new branch in your local repository. To make the branch available to others on a remote
Cit repository, you need to use the Push command.
The illustration shows adding a branch named !l|tJ, using the branch named 5econJ as a starting point.
Impertant: Consistent branching practices are critical to successful source control management. 8e
sure to understand and adhere to your organization's branching strategy.
Create a branch in a repository to isolate specific aspects of your software development efforts and to work in
parallel with other developers.
7e create a brancb in a Subversien repesitery . . .
1. |n the repositories organizer, select the appropriate 8ranches directory in the navigator pane and click
the Add 8ranch button.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
266
2. Lnter a name for the new branch.
3. Prom the pop-up menu, choose an existing branch to serve as the starting point for this new branch.
4. Lnter a log message if you wish.
5. |f appropriate, select the option to automatically check out the new branch.
6. Click Create.
Subversion creates the new branch in the remote repository, to work on it locally, you must first check it
out. Selecting the "Automatically checkout this branch option causes Xcode to check it out for you. |f you
select this option, Xcode opens a Save As dialog so you can specify the name and location for the working
copy of the new branch. |f you do not select this option, you have to check out the branch before you can
work with it.
The illustration shows adding a branch named 5|xtl, using the branch named l|ltl as a starting point.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
267
Impertant: Consistent branching practices are critical to successful source control management. 8e
sure to understand and adhere to your organization's branching strategy.
Switch to another branch of a repository to work on a different line of code development or to prepare for a
branch merge.
7e switcb brancbes . . .
1. |n the navigation pane of the repositories organizer, click the working copy folder for the repository.
2. Click the Switch 8ranch button at the bottom of the Organizer window.
3. |n the Select a 8ranch dialog, choose the branch you want to use from the pop-up menu.
4. Click OK to confirm the switch.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
when the working copy of a branch is selected in the navigation pane, the name and location of the current
branch display at the top of the organizer pane. when the switching operation is successful, this designation
updates to reflect the new current branch.
The video shows switching from the hehch1ey_01 branch to the CaJd111_02 branch of the Ske1ch
svh_^ repository.
Clone a Specific 8ranch
Pather than clone an entire remote repository, you might want to clone only a specific branch. Use the Add
Pepository command for this purpose. ou can also use the Add Pepository command to browse a Subversion
repository without creating a working copy.
7e cIene specific brancbes ef a remete repesitery
1. Open the repositories organizer, click the Add button (+) at the bottom of the navigator pane, and
choose Add Pepository.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
268
2. |n the Add a Pepository dialog, fill in a name for your local working copy and the location of the remote
repository. Click Add.
3. Select the branch for which you want a local working copy and click Clone.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
269
Add a Polder to a Subversion Pepository
when you select a folder such as Trunk for a Subversion repository in the navigation pane of the repositories
organizer, or any folder in the outline view of a Subversion repository, a New Directory button is available at
the bottom of the window. This button creates a new directory, represented as a folder in the organizer. |f no
folder is selected in the outline view, the folder is created at the same level as the top-level folders in the outline
view. |f a folder in the outline view is selected, the new folder is created inside that folder.
7ip: Xcode provides the NewDirectory button in the repositories organizer to help you administer your Subversion
directory. |t's not intended for modifying your Xcode pro|ect. To add a folder to a pro|ect, use the pro|ect navigator
in the workspace window.
Once you create a new Subversion directory, you can add files to it.
Add nonpro|ect files to a repository folder created with the repositories organizer.
7e add fiIes te a new Subversien directery . . .
1. |n the repositories organizer, select the folder to which the files will be added.
2. Click the |mport button at the lower right corner of the window.
3. Locate and select the desired file or folder.
4. Click |mport.
5. Lnter a commit message and click |mport.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
The repositories organizer supports creating a folder in a subversion repository for maintaining and
administering the repository. Por example, you might want to include documents that provide details for
a specific branch or that specify any deviations from your organization's branching and merging protocols.
To add folders and files to a pro|ect, use the pro|ect navigator in the workspace window.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
270
AIternative: ou can drag files to the folder from the Pinder. |f you use this approach, an |mport
dialog appears in which you can add an import message and confirm the operation.
The video shows adding the file BJahch1hg_cohveh11ohs_ahd_pJo1oco1s.1x1 to the Adm1h_0ocs
Subversion directory.
Commit Piles to Add Them to a Pepository
when you edit a file, it is changed locally but the changes are not included in the source control repository.
To add the changes to the repository, you must commit the file. ou must save the file before you can commit
it, but note that saving a file is not the same as committing it to source controlyou must explicitly commit
the file. To see which files have been modified locally but not committed, look for the M badge next to the
filename in the pro|ect navigator. (New files that have never been committed to source control have the A
badge. Piles that are not under source control have a question mark badge.) ou can use the SCM status filter
at the bottom of the pro|ect navigator to display only files with SCM status.
Commit changed files to ensure that those changes are preserved and managed as part of a repository.
7e cemmit fiIes te a repesitery . . .
1. Lnsure that you have saved all file changes.
2. Choose Pile > Source Control > Commit.
3. |n the confirmation dialog, deselect any files that you do not wish to commit.
4. Peview and edit (as appropriate) any changes to be committed.
5. Lnter a commit comment.
6. Click Commit.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
ou can use the confirmation dialog to compare your new version with any past version and to make any
necessary edits in the current version. Any changes you make as you review a file are included in the
committed file and saved in your pro|ect.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
271
|f you're using Subversion, a commit operation copies the changes from selected files into the remote
Subversion repository. Therefore, you must be connected to the repository before you can commit changes.
(Por details, see your repository administrator.)
|f you're using Cit, the commit operation adds your changes to your local working copy. |f you're using a
remote Cit repository, you have to performa push operation to add your committed changes to the shared
repository.
A commit comment is required, the Commit button is disabled until you enter one. Cood comments are
specific, but concise, suggested content includes a brief description of the changes, what they are meant
to accomplish, and UPLs or |D numbers of any relevant bugs. The version editor displays the affected code
together with your name and commit comment, so you can omit information that's in code comments or
that's obvious from looking at the line of code.
The video shows committing changes in four files in the Sketch pro|ect to a local Cit repository.
7ip: To commit one or a small number of files, select those files in the pro|ect navigator,
Control-click one of them, and choose Source Control > Commit Selected Piles from the shortcut
menu.
AIternative: ou can select the working copy in the repositories organizer navigation pane and
click the Commit button at the bottom of the Organizer window.
Peconcile Different 8ranches
when you're ready to merge the code in a separate branch back into the main branch, or when you want to
combine the code in any two branches, you can use the merge facility of your source control systemto reconcile
differences between the branches.
Merge two branches to combine the code in them and reconcile differences between them.
7e merge twe brancbes . . .
1. with the workspace window active, choose Pile > Source Control > Merge.
2. Prom the pop-up menu, choose the branch to merge into the current branch and click Choose.
3. Select a difference or conflict.
4. Use the left and right buttons to specify which file's contents should be used.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
272
5. After resolving all differences and conflicts, click Merge.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
8efore merging, save and commit any unsaved changes in both branches. The Merge command merges a
branch that you choose into the current branch, so you may also need to switch the current branch before
the merge operation.
The left pane of the merge dialog shows what the merged file will look like. The right pane shows the file
with the changes to be merged in. Por each difference between the files, an indicator in the center points
to the file taking precedence. To select a difference, click its indicator. ou use the buttons at the bottom
to set the direction of the merge.
Por example, if the difference is a line of code on the right that's missing from the file on the left (your
working copy) click the Pight button (which sets the indicator to the right) to specify that the line of code
be included in the working copy when the merge is complete. Note that because the left pane shows what
the merged file will look like, you then see this line of code in both panes.
|f a line of code has been changed in both versions of the file being merged, the differences are considered
a conflict and are shown in red. There are two additional buttons for reconciling conflicts by taking the
code lines from both files, either listing the ones in the left file first and those in the right file second, or
vice versa.
To reconcile any differences not handled by the four button choices, you can edit the file in the working
copy.
Update our working Copy from a Pemote Pepository
when two or more people are working on a automata pro|ect, fromtime to time you need to synchronize your
working copy with changes made in the remote repository. ou use the Pull command in Cit or the Update
command in Subversion to do so.
Use a pull operation to update local files with changes from a shared or remote Cit repository to ensure that
your local repository is up to date.
7e puII cbanges frem a remete Cit repesitery . . .
1. Choose Pile > Source Control > Pull.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
273
2. |n the Pull dialog, select a file in the navigation pane.
3. Select a difference to reconcile by clicking its indicator.
4. Use the left and right buttons to specify how the difference is to be reconciled.
5. After reconciling all differences, click Pull to complete the operation.
8efore you can push changes in your local repository to a shared repository, Cit requires a pull operation,
in which you reconcile differences between the two repositories. This reconciliation helps prevent your
accidentally modifying or undoing other developers' changes.
ou need to save changes you've made and commit them to your local repository before pulling changes
from the shared repository.
|n the Pull dialog, you select a difference by clicking the indicator between the two files. ou then click one
of the four buttons at the bottom to choose how that difference is to be reconciled. The indicator updates
to reflect your choice.
A difference in which a line of code has been changed in both versions of the file is considered a conflict,
and its indicator is a question mark. ou can't complete the pull operation until you specify how to resolve
all conflicts.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
274
|f you wish, you can edit the local revision of the file in the Pull dialog to reconcile any differences not
handled by the four button choices.
|n busy times , multiple developers may attempt to submit changes to the shared repository at the same
time. |f another developer's submission completes before yours, Xcode informs you that you must first
perform a new pull operation. |n larger organizations, particularly |ust prior to a product release, you may
find that you have to pull changes more than once.
After the pull operation, you have to commit the changes files in your local repository that are updated by
the pull operation.
The illustration shows the Pull dialog, with a conflict selected.
7ip: To pull changes for one file or a small number of files, select those files in the pro|ect
navigator, Control-click one of them, and choose Source Control > Update Selected Piles from
the shortcut menu that appears.
Update your local working copy with changes from a shared or remote Subversion repository to ensure that
your local copy is up to date.
7e update cbanges frem a remete Subversien repesitery . . .
1. Choose Pile > Source Control > Update.
2. |n the Update dialog, select a difference to reconcile.
3. Use the left and right buttons to specify which file's contents should be used.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
275
4. After reconciling all differences, click Update to complete the operation.
with a shared repository, there is a potential for one developer's changes to undo or overwrite those of
another developer. To prevent this problem, Subversion requires that you update your local copy with the
changes already submitted to the shared repository.
Nete: ou must have an active network connection to the server that holds the remote repository.
ou need to save changes you've made and commit them to your local repository before updating files
with changes from the shared repository.
|n the update dialog, you select a difference by clicking the indicator between the two files. ou then click
one of the four buttons at the bottom to choose how that difference is to be reconciled. The indicator
updates to reflect your choice.
A difference in which a line of code has been changed in both versions of the file is considered a conflict,
and its indicator is a question mark. ou can't complete the update operation until you specify how to
resolve all conflicts.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
276
|f you wish, you can edit the local revision of the file in the update dialog to reconcile any differences not
handled by the four button choices.
|n busy times , multiple developers may attempt to submit changes to the shared repository at the same
time. |f another developer's submission completes before yours, Xcode informs you that you must first
perform a new update operation. |n larger organizations, particularly |ust prior to a product release, you
may find that you have to update more than once.
After the update, you have to commit the changes files in your local repository that are updated by the
update.
The illustration shows the dialog for reconciling differences, with a conflict selected.
7ip: To update one file or a small number of files, select those files in the pro|ect navigator,
Control-click one of them, and choose Source Control > Update Selected Piles from the shortcut
menu that appears.
Send our working Copy to the Pemote Cit Pepository
|f you're using a remote Cit repository, when you're ready to share your work with the other members of your
team, you can push your files back to the remote repository. (|f you're using Subversion, the commit command
updates the remote repository.) |f you cloned your working copy from a repository, you should see the remote
repository in the repository organizer. 8efore performing a push, you have to save and commit all changes
and execute the Pull command to reconcile any differences between your version and the one on the server.
Then, choose Pile > Source Control > Push.
Save and Revert Cbanges te Prejects
work with Cit and Subversion
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
277
Save |nternal Pro|ect Piles in Pepositories
|n Xcode 4.1 and later, you can use repositories to view internal pro|ect files (for example, schemes and user
interface settings) when looking at SCM details in the SCM commit and update workflows. ou can use this
facility to save and keep track of versions of pro|ect files in the same way as you save and keep track of source
files. Pigure 11-8 shows a commit dialog displaying two versions of a scheme.
Iigure 11-8 A scheme in the commit dialog
Compare Pevisions
ou use the Xcode version editor to compare revisions. To compare any two versions of a file under source
control in a side-by-side view, select the file in the pro|ect navigator and click the version editor button (
). Use the |ump bar underneath either editor pane to select the version of the file to compare with
the one in the other pane (Pigure 11-9). ou can select any committed version of that file in any branch.
Save and Revert Cbanges te Prejects
Compare Pevisions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
278
8uttons under the version editor ( ) allow you to show a file comparison and timeline, change logs
for the file, or individual change annotations ("blame) for each line of the file.
Iigure 11-9 Comparing two revisions of a file with the version editor
ou can edit the current working copy of the file in the version editor and you can copy code from an older
version and paste it into the current version.
Select Specific Pevisions
Click the timeline icon ( ) in the center column to show a visual timeline of all repository versions, use the
sliders to control which version is displayed on each side.
Use the version timeline to choose file versions based on their chronological order.
7e cempare versiens ef a fiIe witb tbe timeIine . . .
1. with a source file open in the version editor, click the Comparison button.
2. Click the timeline viewer icon.
3. 8rowse the timeline with your pointer to reach the version you want to compare.
Save and Revert Cbanges te Prejects
Compare Pevisions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
279
4. Click the right triangular indicator to open that version in the right editing pane.
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
!""#$%"#&'()#*"+,-./#.0#$%-,#
1.234"/$#$.#*-"5#$%"#*-1".6
The version timeline is available in the comparison view. Clicking the timeline viewer icon displays the
timeline between the two editing panes.
ou move the pointer (cursor) up or down through the timeline to browse the available versions. versions
are listed chronologically, with a line for each version, newer versions are at the bottom of the timeline.
Lach ma|or division in the timeline groups revisions submitted within a twenty-four hour period.
As you reach each version in the timeline, additional information for that version is displayed in an annotation.
when you find the version you want, click the left or right indicator triangle to display that version in the
corresponding editor pane. Por example, the video shows choosing an older version of a file from the
repository (for display on the right) to compare it with the newer local version of that file (displayed on the
left).
Clicking the left indicator triangle allows you to compare another version in the left pane with the version
in the right.
Peview |ndividual Changes
|n blame mode, the current revision of the file is displayed along with the last revision that modified each line
of the file.
7e see wbe is respensibIe fer tbe Iast revisien ef a Iine ef cede
!
Click the blame mode button at the bottom of the version editor.
Save and Revert Cbanges te Prejects
Compare Pevisions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
280
Lach blame mode entry is aligned with the line in the file where the change was made. The entry
includes the name of the person who committed the change, the date, and the |D of the commit.
7ip: Next to the entry is an arrow button. Click the arrow next to any change that interests you to see
that change displayed in Comparison mode.
view All Pevisions Chronologically
To review all revisions to a file listed in chronological order, use Log mode. Lach change is listed individually,
and you can click the arrow next to the log entry to see the change displayed in Comparison mode.
7e review aII revisiens te a fiIe
!
Click the log mode button at the bottom of the version editor.
Save and Revert Cbanges te Prejects
Compare Pevisions
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
281
All the log entries for the file are listed in chronological order and include the name of the person who
committed the change, the date, the |D of the commit, and the commit comments.
7ip: Click the arrow next to any entry to see that change displayed in Comparison mode.
7ip: ou can view all the commits for a pro|ect, listed by file, in the Organizer window. See "why Use Source
Control!" (page 277) for details.
Distribute our Program
Archives package your products for distribution. Use archives to distribute your program through your own
distribution mechanismor to submit an application to iTunes Connect for inclusion in the iOS or Mac app store.
To build your pro|ect and save the resulting application or a disk image of the set of build products, choose
Product > Archive. Xcode creates an archive of your pro|ect using the build configuration and name you
specified in the Archive pane of the scheme editor ("Create an Archive for Sharing or Submitting our
Program" (page !)) and saves the archive in the location specified in the Locations pane of Xcode preferences.
Save and Revert Cbanges te Prejects
Distribute our Program
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
282
To see the archives for your pro|ect, open the archives organizer (Pigure 11-10). ou can add a comment by
clicking in the text field in the Comment column.
Iigure
11-10
The archives organizer
Por details on how to use archives to distribute your products, see "Distribute our App" (page 284).
Save and Revert Cbanges te Prejects
Distribute our Program
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
283
ou distribute your app to share it with other persons in your development team, for user testing, or for
publication on the App Store.
Archive our App
8efore you can distribute your app, you have to archive it.
Archive your product for submission to iTunes Connect or for sharing with others. Schemes have an Archive
action with settings you use to customize the archive that Xcode creates when you choose Product > Archive.
7e arcbive yeur app . . .
1. Prom the Scheme toolbar menu, choose a scheme.
2. Prom the same menu, choose Ldit Scheme to display the scheme dialog.
3. |n the left column, select Archive.
4. Choose a build configuration.
5. Specify a name for the archive and click OK.
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
284
Distribute our App
6. Choose Product > Archive.
An archive is a bundle that includes your product along with symbol information. ou can build an archive
to seed an application for testing or to validate and submit an application to iTunes Connect.
our new archive appears in the Archives list in the Organizer window, unless you turn off this option. Lach
archive is identified in the archives organizer with the date and time it was created. Por more information,
see the related article on the archives organizer.
Impertant: |f your app uses static libraries, you must ensure that those libraries are part of the app binary.
To learn how, see "Developing a Static Library and |ncorporating |t in our App".
validate our App
8efore distributing your app, you should validate the app archive to ensure that it passes essential iTunes
Connect tests.
Distribute eur App
validate our App
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
285
validate your app to find out whether it meets minimum submission requirements.
7e vaIidate yeur app . . .
1. |n the Archives organizer, select the application archive you want to validate, and click validate.
2. Por Mac distribution, select the distribution method, and click Next.
3. Pollow the instructions to complete the process.
8efore submitting your app for publication on the App Store, you should validate it to ensure that it passes
standard iTunes Connect checks.
The screenshot shows the validation-method pane that appears for Mac distribution. This pane doesn't
appear for iOS distribution.
Distribute eur App
validate our App
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
286
7reubIesbeeting: |f Xcode doesn't find an iTunes Connect application record for your application,
the dialog "No suitable application records were found appears. This dialog also appears when
the application record state is not at least "waiting for Upload.
!
Lnsure that an application record exists for your application in iTunes Connect.
!
Lnsure that the application record status is at least "waiting to Upload.
Distribute our iOS App
Distribute your iOS app to users or other members of your development team.
7e distribute yeur iDS app . . .
1. |n the Archives organizer, select the application archive you want to distribute, and click Distribute.
2. Select the distribution method, and click Next.
Distribute eur App
Distribute our iOS App
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
287
3. Pollow the instructions to complete the process.
Specifying the distribution method:
!
To submit the app for publication to the iOS App Store, select "Submit to the iOS App Store.
!
To save a package of the app for enterprise or ad hoc (user testing) deployment, select "Save for
Lnterprise or Ad-Hoc Deployment.
!
To create an Xcode archive of the app to distribute to other members of your team, select "Lxport as
Xcode Archive.
when using enterprise distribution, Xcode saves an enterprise-distribution manifest (as a property list file)
alongside the shared archive. Por details about the contents of the enterprise-distribution manifest, see
developer.apple.com/programs/ios/enterprise.
|f you saved a package or an Xcode archive of the app, send it to the people to whomyou want to distribute
it.
Distribute eur App
Distribute our iOS App
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
288
To learn more about distributing your iOS app, see "Distributing Apps".
Distribute our Mac App
Distribute your Mac app to users or other members of your development team.
7e distribute yeur Mac app . . .
1. |n the Archives organizer, select the application archive you want to distribute, and click Distribute.
2. Select the distribution method, and click Next.
3. Pollow the instructions to complete the process.
Here's how you select the distribution method:
!
To submit the app for publication to the Mac App Store, select "Submit to the Mac App Store.
Distribute eur App
Distribute our Mac App
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
289
!
To create an Xcode archive, an installation package, or a binary file of the app, select "Lxport as and
choose the file format from the pop-up menu.
To learn more about distributing your Mac app, see "Submitting to the Mac App Store".
Distribute eur App
Distribute our Mac App
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
290
This table describes the changes to \coJe 4 uset Cu|Je .
Netes Date
Made available in PDP. 2012-09-19
Added chapter about saving and reverting changes to files. 2012-06-11
Added "Save and Pevert Changes to Piles" (page 244).
Added features new in Xcode 4.2. 2011-10-12
Added features new in Xcode 4.1. 2011-08-10
The following sections contain new information:
"Close a Pro|ect or a workspace" (page 65), "Open a P|le uickly" (page
130), "view Preprocessor or Assembly Output" (page 143), "Upgrade
|nterface 8uilder Piles That Use Plug-ins, "Configure Sandboxing,
"Customize our 8uild and Pun workflow" (page !), "Take a Snapshot
of our Pro|ect" (page 252), "Save |nternal Pro|ect Piles in Pepositories
" (page 278).
Made editorial and format changes throughout. 2011-05-07
New document that explains how to use Xcode 4 to develop software for
iOS and OS X.
2011-03-02
2012-09-19 | 2012 Apple |nc. All Pights Peserved.
291
Document Pevision History
Apple |nc.
2012 Apple |nc.
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 |nc., 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
Apple's copyright notice.
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.
Apple |nc.
1 |nfinite Loop
Cupertino, CA 95014
408-996-1010
Apple, the Apple logo, AppleScript, Cocoa, Cocoa
Touch, Pinder, |nstruments, iPad, iPhone, iPod,
iPod touch, iTunes, Leopard, Logic, Mac, Mac OS,
Ob|ective-C, OS X, Safari, Sand, Snow Leopard,
Spotlight, and Xcode are trademarks of Apple
|nc., registered in the U.S. and other countries.
Petina is a trademark of Apple |nc.
App Store and Mac App Store are service marks
of Apple |nc.
OpenCL is a registered trademark of Silicon
Craphics, |nc.
iOS is a trademark or registered trademark of
Cisco in the U.S. and other countries and is used
under license.
ven tbeugb AppIe bas reviewed tbis decument,
APPL MAkS ND WARRAN7 DR RPRSN7A7IDN,
I7HR XPRSS DR IMPLID, WI7H RSPC7 7D 7HIS
DDCUMN7, I7S UALI7, ACCURAC,
MRCHAN7A8ILI7, DR II7NSS IDR A PAR7ICULAR
PURPDS. ASARSUL7, 7HISDDCUMN7ISPRDVIDD
AS IS, AND DU, 7H RADR, AR ASSUMINC 7H
N7IR RISk AS 7D I7S UALI7 AND ACCURAC.
IN ND VN7 WILL APPL 8 LIA8L IDR DIRC7,
INDIRC7, SPCIAL, INCIDN7AL, DRCDNSUN7IAL
DAMACS RSUL7INC IRDM AN DIC7 DR
INACCURAC IN 7HIS DDCUMN7, even if advised ef
tbe pessibiIity ef sucb damages.
7H WARRAN7 AND RMDIS S7 IDR7H A8DV
AR XCLUSIV AND IN LIU DI ALL D7HRS, DRAL
DR WRI77N, XPRSS DR IMPLID. Ne AppIe deaIer,
agent, er empIeyee is autberized te make any
medificatien, extensien, er additien te tbis warranty.
Seme states de net aIIew tbe excIusien er Iimitatien
ef impIied warranties er IiabiIity fer incidentaI er
censequentiaI damages, se tbe abeve Iimitatien er
excIusien may net appIy te yeu. 7bis warranty gives
yeu specific IegaI rigbts, and yeu may aIse bave etber
rigbts wbicb vary frem state te state.

Anda mungkin juga menyukai