Tải bản đầy đủ
Chapter 6. Anatomy of an Xcode Project

Chapter 6. Anatomy of an Xcode Project

Tải bản đầy đủ

New Project
Even before you’ve written any code, an Xcode project is quite elaborate. To see this,
let’s make a new, essentially “empty” project; you’ll find that it isn’t empty at all.
1. Start up Xcode and choose File → New → Project.
2. The “Choose a template” dialog appears. The template is your project’s initial set
of files and settings. When you pick a template, you’re really picking an existing
folder full of files; this folder is hidden deep inside the Xcode bundle, at
Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/
Xcode/Templates/Project Templates/iOS/Application. This template folder will
essentially be copied, and a few values will be filled in, in order to create your
project.
So, in this case, select iOS; under Application, select the Single View app tem‐
plate. Click Next.
3. You are now asked to provide a name for your project (Product Name). Let’s call
our new project Empty Window.
In a real project, you should give some thought to the project’s name, as you’re
going to be living in close quarters with it. As Xcode copies the template folder,
it’s going to use the project’s name to “fill in the blank” in several places, includ‐
ing the name of the app. Thus, whatever you type at this moment is something
you’ll be seeing throughout your project. You are not locked into the name of
your project forever, though, and there’s a separate setting allowing you to change
at any time the name of the app that it produces. I’ll talk later about name
changes (“Renaming Parts of a Project” on page 331).
It’s fine to use spaces in a project name. Spaces are legal in the project name, the
app name, and the various names of files and folders that Xcode will generate
automatically; and in the few places where spaces are problematic (such as the
bundle identifier, which I’ll discuss in a moment), the name you type as the Prod‐
uct Name will have its spaces converted to hyphens. But do not use any other
punctuation in your project name! Such punctuation can cause Xcode features to
break in subtle ways.
4. New in Xcode 8 is the Team pop-up menu. Ignore this for now; I’ll discuss its
significance in Chapter 9. Ignore the Organization Name as well; it is used only
in some automatically generated code comments.
5. Note the Organization Identifier field. The first time you create a project, this
field will be blank, and you should fill it in. The goal here is to create a unique
string identifying you or your organization. The convention is to start the organi‐
zation identifier with com. and to follow it with a string (possibly with multiple
dot-components) that no one else is likely to use. For example, I use

294

|

Chapter 6: Anatomy of an Xcode Project

com.neuburg.matt. Every app on a device or submitted to the App Store needs a
unique bundle identifier. Your app’s bundle identifier, which is shown in gray
below the organization identifier, will consist of the organization identifier plus a
version of the project’s name; if you give every project a unique name within
your personal world, the bundle identifier will uniquely identify this project and
the app that it produces (or you can change the bundle identifier manually later if
necessary).

6. The Language pop-up menu lets you choose between Swift and Objective-C. This
choice is not positively binding; it dictates the initial structure and code of the
project template, but you are free to add Swift files to an Objective-C project, or
Objective-C files to a Swift project. You can even start with an Objective-C
project and decide later to convert it completely to Swift. (See “Bilingual Targets”
on page 575.) For now, choose Swift.
7. Make sure the Devices pop-up menu is set to iPhone. Again, this choice is not
positively binding; but for now, let’s assume that our app is to run on iPhone
only.
8. Make sure Use Core Data, Include Unit Tests, and Include UI Tests are not
checked. Click Next.
9. You’ve now told Xcode how to construct your project. Basically, it’s going to copy
the Single View Application.xctemplate folder from within the Project Templates
folder I mentioned earlier. But you need to tell it where to copy this template
folder to. That’s why Xcode is now presenting a Save dialog with a Create button.
You are to specify the location of a folder that is about to be created — the project
folder for this project. The project folder can go just about anywhere, and you can
move it after creating it. I usually create new projects on the Desktop.
10. Xcode also offers, through a checkbox, to create a git repository for your project.
(You might need to click Options to see the checkbox.) In real life, this can be a
great convenience (see Chapter 9), but for now, uncheck that checkbox. Click
Create.
11. The Empty Window project folder is created on disk (on the Desktop, if that’s the
location you just specified), and the project window for the Empty Window
project opens in Xcode.
The project we’ve just created is a working project; it really does build an iOS app
called Empty Window. To see this, make sure that the scheme and destination in the
project window’s toolbar are listed as Empty Window → iPhone 6. (The scheme and
destination are actually pop-up menus, so you can click on them to change their val‐
ues if needed.) Choose Product → Run. After some delay, the iOS Simulator applica‐
tion eventually opens and displays your app running — an empty white screen.

New Project

|

295

To build a project is to compile its code and assemble the compiled code,
together with various resources, into the actual app. Typically, if you want to
know whether your code compiles and your project is consistently and correctly
constructed, you’ll build the project (Product → Build). Alternatively, you can
compile an individual file (choose Product → Perform Action → Compile [File‐
name]). To run a project is to launch the built app, in the Simulator or on a con‐
nected device; if you want to know whether your code works as expected, you’ll
run the project (Product → Run), which automatically builds first if necessary.

The Project Window
An Xcode project embodies a lot of information about what files constitute the
project and how they are to be used when building the app, such as:
• The source files (your code) that are to be compiled
• Any .storyboard or .xib files, graphically expressing interface objects to be instan‐
tiated as your app runs
• Any resources, such as icons, images, or sound files, that are to be part of the app
• All settings (instructions to the compiler, to the linker, and so on) that are to be
obeyed as the app is built
• Any frameworks that the code will need when it runs
A single Xcode project window presents all of this information, as well as letting you
access, edit, and navigate your code, plus reporting the progress and results of such
procedures as building or debugging an app and more. This window displays a lot of
information and embodies a lot of functionality! A project window is powerful and
elaborate; learning to navigate and understand it takes time. Let’s pause to explore
this window and see how it is constructed.
A project window has four main parts (Figure 6-1):
1. On the left is the Navigator pane. Show and hide it with View → Navigators →
Show/Hide Navigator (Command-0) or with the first View button at the right
end of the toolbar.
2. In the middle is the Editor pane (or simply “editor”). This is the main area of a
project window. A project window nearly always displays an Editor pane, and can
display multiple Editor panes simultaneously.
3. On the right is the Utilities pane. Show and hide it with View → Utilities →
Show/Hide Utilities (Command-Option-0) or with the third View button at the
right end of the toolbar.

296

|

Chapter 6: Anatomy of an Xcode Project

Figure 6-1. The project window
4. At the bottom is the Debug pane. Show and hide it with View → Debug Area →
Show/Hide Debug Area (Command-Shift-Y) or with the second View button at
the right end of the toolbar.
All Xcode keyboard shortcuts can be customized; see the Key Bindings pane of
the Preferences window. Keyboard shortcuts that I cite are the defaults.

The Navigator Pane
The Navigator pane is the column of information at the left of the project window.
Among other things, it’s your primary mechanism for controlling what you see in the
main area of the project window (the editor). An important use pattern for Xcode is:
you select something in the Navigator pane, and that thing is displayed in the editor.
It is possible to toggle the visibility of the Navigator pane (View → Navigators →
Hide/Show Navigator, or Command-0); for example, once you’ve used the Navigator
pane to reach the item you want to see or work on in the editor, you might hide the
Navigator pane temporarily to maximize your screen real estate (especially on a
smaller monitor). You can change the Navigator pane’s width by dragging the vertical
line at its right edge.
The Navigator pane itself can display eight different sets of information; thus, there
are actually eight navigators. These are represented by the eight icons across its top;
to switch among them, use these icons or their keyboard shortcuts (Command-1,
Command-2, and so on). If the Navigator pane is hidden, pressing a navigator’s key‐
board shortcut both shows the Navigator pane and switches to that navigator.

The Project Window

|

297

Figure 6-2. The Project navigator
Depending on your settings in the Behaviors pane of Xcode’s preferences, a navigator
might show itself automatically when you perform a certain action. For example, by
default, when you build your project, if warning messages or error messages are gen‐
erated, the Issue navigator will appear. This automatic behavior will not prove trou‐
blesome, because it is generally precisely the behavior you want, and if it isn’t, you can
change it; plus you can easily switch to a different navigator at any time.
Let’s begin experimenting immediately with the various navigators:
Project navigator (Command-1)
Click here for basic navigation through the files that constitute your project
(Figure 6-2). For example, in the Empty Window folder (these folder-like things
in the Project navigator are actually called groups), click AppDelegate.swift to
view its code in the editor.
At the top level of the Project navigator, with a blue Xcode icon, is the Empty
Window project itself; click it to view the settings associated with your project
and its targets. Don’t change anything here without knowing what you’re doing!
I’ll talk later in this chapter about what these settings are for.
The filter bar at the bottom of the Project navigator lets you limit what files are
shown; when there are many files, this is great for quickly reaching a file with a
known name. For example, try typing “delegate” in the filter bar search field.
Don’t forget to remove your filter when you’re done experimenting.
Once you’ve filtered a navigator, it stays filtered until you remove the filter —
even if you close the project! A common mistake is to filter a navigator, forget
that you’ve done so, fail to notice the filter (because you’re looking at the naviga‐
tor itself, not down at the bottom where the filter bar is), and wonder, “Hey,
where did all my files go?”

Symbol navigator (Command-2)
A symbol is a name, typically the name of a class or method. Among other things,
this can be useful for navigating your code. For example, highlight the first two
298

|

Chapter 6: Anatomy of an Xcode Project

Figure 6-3. The Find navigator
icons in the filter bar (the first two are blue, the third is dark), and see how
quickly you can reach the definition of AppDelegate’s applicationDidBecomeActive(_:) method.
Try highlighting the filter bar icons in various ways to see how the contents of the
Symbol navigator change. Type in the search field in the filter bar to limit what
appears in the Symbol navigator; for example, try typing “active” in the search
field, and see what happens.
When the second filter icon is not highlighted, you are shown all symbols,
including those defined by Swift and those defined by Cocoa (Figure 4-1). This is
a great way to learn what object types exist, and to reach the headers where those
types are declared (an important form of documentation: see Chapter 8).

Find navigator (Command-3)
This is a powerful search facility for finding text globally in your project. You can
also summon the Find navigator with Find → Find in Project (Command-ShiftF). The words above the search field show what options are currently in force;
they are pop-up menus, so click one to change the options. Try searching for
“delegate” (Figure 6-3). Click a search result to jump to it in your code.
Below the search field, at the left, is the current search scope. This limits what files
will be searched. Click it to see the Search Scopes panel. You can limit the search
to a group (folder) within your project. You can also define a new scope: click
New Scope to summon the scope configuration popover, where you can examine
your options. Scopes are defined per user, not per project; scopes that you create
here will appear in other projects.
You can type in the other search field, the one in the filter bar at the bottom, to
limit further which search results are displayed. (I’m going to stop calling your
attention to the filter bar now, but every navigator has it in some form.)
Issue navigator (Command-4)
You’ll need this navigator primarily when your code has issues. This doesn’t refer
to emotional instability; it’s Xcode’s term for warning and error messages emitted
The Project Window

|

299

when you build your project. New in Xcode 8, the Issue navigator, in addition to
displaying buildtime issues (compile errors and warnings), can also display cer‐
tain runtime issues (such as leaks, when using the memory sanitizer, as I’ll
explain in Chapter 9).
To see the Issue navigator in action, let’s give your code a buildtime issue. Navi‐
gate (as you already know how to do, in at least three different ways) to the file
AppDelegate.swift, and in the blank line after the last comment at the top of the
file’s contents, above the import line, type howdy. Build the project (CommandB). The Issue navigator, in its Buildtime pane, will display some error messages,
showing that the compiler is unable to cope with this illegal word appearing in an
illegal place. Click an issue to see it within its file. In your code, issue “balloons”
may appear to the right of lines containing issues; if you’re distracted or ham‐
pered by these, toggle their visibility with Editor → Issues → Hide/Show All
Issues (Command-Control-M).
Now that you’ve made Xcode miserable, select “howdy” and delete it; save and
build again, and your issues will be gone. If only real life were this easy!
Test navigator (Command-5)
This navigator lists test files and individual test methods and permits you to run
your tests and see whether they succeeded or failed. A test is code that isn’t part
of your app; rather, it calls a bit of your app’s code to see whether it behaves as
expected. I’ll talk more about tests in Chapter 9.
Debug navigator (Command-6)
By default, this navigator will appear when your code is paused while you’re
debugging it. There is not a strong distinction in Xcode between running and
debugging; the milieu is the same. The difference is mostly a matter of whether
breakpoints are obeyed (more about that, and about debugging in general, in
Chapter 9).
To see the Debug navigator in action, you’ll need to give your code a breakpoint.
Navigate once more to the file AppDelegate.swift, select in the line that says
return true, and choose Debug → Breakpoints → Add Breakpoint at Current
Line to make a blue breakpoint arrow appear on that line. Run the project. By
default, as the breakpoint is encountered, the Navigator pane switches to the
Debug navigator, and the Debug pane appears at the bottom of the window. This
overall layout (Figure 6-4) will rapidly become familiar as you debug your
projects.
The Debug navigator starts with several numeric and graphical displays of profil‐
ing information (at a minimum, you’ll see CPU, Memory, Disk, and Network);
click one to see extensive graphical information in the editor. This information
allows you to track possible misbehavior of your app as you run it, without the
300

|

Chapter 6: Anatomy of an Xcode Project

Figure 6-4. The Debug layout
added complexity of running the Instruments utility (discussed in Chapter 9). To
toggle the visibility of the profiling information at the top of the Debug navigator,
click the “gauge” icon (to the right of the process’s name).
The Debug navigator also displays the call stack, with the names of the nested
methods in which a pause occurs; as you would expect, you can click on a
method name to navigate to it. You can shorten or lengthen the list with the first
button in the filter bar at the bottom of the navigator. The second icon to the
right of the process’s name summons a pop-up menu that lets you toggle between
display by thread (View Process by Thread) and display by queue (View Process
by Queue). I’ll discuss in Chapter 9 what the other two entries in that pop-up
menu do.
The Debug pane, which can be shown or hidden at will (View → Debug Area →
Hide/Show Debug Area, or Command-Shift-Y), consists of two subpanes:
The variables list (on the left)
It is populated with the variables in scope for the selected method in the call
stack at the point where we are paused.
The console (on the right)
Here the debugger displays text messages; that’s how you learn of exceptions
thrown by your running app, plus you can have your code deliberately send
you log messages describing your app’s progress and behavior. Such messages
are important, so keep an eye on the console as your app runs. You can also
use the console to enter commands to the debugger. This can often be a bet‐
ter way to explore values during a pause than the variables list.
Either the variables list or the console can be hidden using the two buttons at the
bottom right of the pane. The console can also be summoned by choosing View
→ Debug Area → Activate Console.
The Project Window

|

301

Figure 6-5. Viewing a report
Breakpoint navigator (Command-7)
This navigator lists all your breakpoints. At the moment you have only one, but
when you’re actively debugging a large project with many breakpoints, you’ll be
glad of this navigator. Also, this is where you create special breakpoints (such as
symbolic breakpoints), and in general it’s your center for managing existing
breakpoints. We’ll return to this topic in Chapter 9.
Report navigator (Command-8)
This navigator lists your recent major actions, such as building or running
(debugging) your project. Click a listing to see (in the editor) the report gener‐
ated when you performed that action. The report might contain information that
isn’t displayed in any other way, and also it lets you dredge up console messages
from the recent past (“What was that exception I got while debugging a moment
ago?”).
For example, by clicking on the listing for a successful build, and by choosing to
display All and All Messages using the filter switches at the top of the report, we
can see the steps by which a build takes place (Figure 6-5). To reveal the full text
of a step, click on that step and then click the Expand Transcript button that
appears at the far right (and see also the menu items in the Editor menu).
When navigating by clicking in the Navigator pane, modifications to your click can
determine where navigation takes place. By default, Option-click navigates in an
assistant pane (discussed later in this chapter), double-click navigates by opening a
302

|

Chapter 6: Anatomy of an Xcode Project

new window, and Option-Shift-click summons a little heads-up pane where you can
specify where to navigate (a new window, a new tab, or a new assistant pane). For the
settings that govern these click modifications, see the Navigation pane of Xcode’s
preferences.

The Utilities Pane
The Utilities pane is the column at the right of the project window. It contains inspec‐
tors that provide information about the current selection or its settings; if those set‐
tings can be changed, this is where you change them. It also contains libraries that
function as a source of objects you may need while editing your project. The Utilities
pane’s importance emerges mostly when you’re editing a .storyboard or .xib file
(Chapter 7). But it can be useful also while editing code, because Quick Help, a form
of documentation (Chapter 8), is displayed here as well, plus the Utilities pane is the
source of code snippets (Chapter 9). To toggle the visibility of the Utilities pane,
choose View → Utilities → Hide/Show Utilities (Command-Option-0). You can
change the Utilities pane’s width by dragging the vertical line at its left edge.
The Utilities pane consists of numerous palettes, which are clumped into multiple
sets, which are themselves divided into two major groups: the top half of the pane
and the bottom half of the pane. You can change the relative heights of these two
halves by dragging the horizontal line that separates them.
The top half
What appears in the top half of the Utilities pane depends on what’s selected in
the current editor. For example:
A code file is being edited
The top half of the Utilities pane shows either the File inspector or Quick
Help. Toggle between them with the icons at the top of this half of the Utilit‐
ies pane, or with their keyboard shortcuts (Command-Option-1, CommandOption-2). The File inspector is rarely needed, but Quick Help can be useful
because it displays documentation (Chapter 8). The File inspector consists of
multiple sections, each of which can be expanded or collapsed by clicking its
header.
A .storyboard or .xib file is being edited
The top half of the Utilities pane shows, in addition to the File inspector and
Quick Help, the Identity inspector (Command-Option-3), the Attributes
inspector (Command-Option-4), the Size inspector (Command-Option-5),
and the Connections inspector (Command-Option-6). These can consist of
multiple sections, each of which can be expanded or collapsed by clicking its
header.
Other forms of editing may cause other inspector combinations to appear here.
The Project Window

|

303

The bottom half
The bottom half of the Utilities pane shows one of four libraries. Toggle between
them with the icons at the top of this half of the Utilities pane, or with their key‐
board shortcuts. They are the File Template library (Command-OptionControl-1), the Code Snippet library (Command-Option-Control-2), the Object
library (Command-Option-Control-3), and the Media library (CommandOption-Control-4). The Object library is the most important; you’ll use it heavily
when editing a .storyboard or .xib file.
To see a help pop-up describing the currently selected item in a library, press
Spacebar.

The Editor
In the middle of the project window is the editor. This is where you get actual work
done, reading and writing your code (Chapter 9), or designing your interface in
a .storyboard or .xib file (Chapter 7). The editor is the core of the project window. You
can hide the Navigator pane, the Utilities pane, and the Debug pane, but there is no
such thing as a project window without an editor (though you can cover the editor
completely with the Debug pane).
The editor provides its own form of navigation, the jump bar across the top. Not only
does the jump bar show you hierarchically what file is currently being edited, but also
it allows you to switch to a different file. In particular, each path component in the
jump bar is also a pop-up menu. These pop-up menus can be summoned by clicking
on a path component, or by using keyboard shortcuts (shown in the second section of
the View → Standard Editor submenu). For example, Control-4 summons a hierarch‐
ical pop-up menu, which can be navigated entirely with the keyboard, allowing you to
choose a different file in your project to edit. Moreover, each pop-up menu in the
jump bar also has a filter field; to see it, summon a pop-up menu from the jump bar
and start typing. Thus you can navigate your project even if the Project navigator isn’t
showing.
The symbol at the left end of the jump bar (Control-1) summons a hierarchical menu
(the Related Items menu) allowing navigation to files related to the current one. What
appears here depends not only on what file is currently being edited but on the cur‐
rent selection within that file. This is an extremely powerful and convenient menu,
and you should take time to explore it. You can navigate to related class files (Super‐
classes, Subclasses, and Siblings; siblings are classes with the same superclass); you
can view methods called by the currently selected method, and that call the currently
selected method. Choose Generated Interface to view the public API of a Swift file or
Objective-C header file as seen by Swift, or Original Source to switch from a Swift
generated interface to the Objective-C original.

304

|

Chapter 6: Anatomy of an Xcode Project