- Creating New Projects
- Building Hello World the Template Way
- Using the Simulator
- The Minimalist Hello World
- Converting Interface Builder Files to Their Objective-C Equivalents
- Using the Debugger
- Memory Management
- Recipe: Using Instruments to Detect Leaks
- Recipe: Using Instruments to Monitor Cached Object Allocations
- Analyzing Your Code
- Building for the iOS Device
- Detecting Simulator Builds with Compile-Time Checks
- Performing Runtime Compatibility Checks
- Pragma Marks
- Preparing for Distribution
- Over-the-Air Ad Hoc Distribution
- Submitting to the App Store
Building Hello World the Template Way
Xcode’s preconfigured templates offer the easiest path to creating a Hello World–style sample application. In the following steps, you create a new project, edit it to say “Hello World,” and run it on the iOS simulator. As you build your first Xcode project, you’ll discover some of the key development pathways.
Create a New Project
With the iOS SDK installed, launch Xcode. Close the Xcode Welcome page; it’s the window that says “Welcome to Xcode” and offers options such as Create a New Xcode Project. This window continues to appear until you uncheck “Show this window when Xcode launches” before closing it. Thereafter, you can access the page via Window > Welcome to Xcode (Command-Shift-1).
To create a new project, choose File > New > New Project (Command-Shift-N). This opens the template selection window shown in Figure 3-1. By default, the template selection window is embedded in a large new window, which is called a “workspace.” Workspaces embed all of Xcode’s editing and inspector features into a single window.
The left column in Figure 3-1 includes three iPhone project categories. These are Application (that is, the screen you see in Figure 3-1) Framework & Library (for creating static Cocoa Touch library modules), and Other (which initially contains a single, empty project style).
Choose Application > Single View Application and then click Next. Xcode opens a “Choose options for your new project:” screen, as shown in Figure 3-2. Enter Hello World for the project name and set the company identifier (for example, com.sadun). Company identifiers typically use reverse domain naming. The new application identifier appears below this in light grey text. In my case, this is com.sadun.Hello-World. Enter an optional class prefix. Xcode uses this to prepend template classes. If you enter ES, for example, Xcode creates ESAppDelegate.h and .m files. Choose Universal from the Device Family pop-up. Leave Use Storyboard checked. Leave Include Unit Tests unchecked. Click Next.
Figure 3-2. Once you set your company identifier, Xcode applies your settings between successive runs. This helps you avoid what was one of the most irritating features of previous Xcode releases—having to remember to edit your settings from “com.yourcompany” for each project.
Choose where to save the new project (such as the desktop) and click Save. A new Hello World Xcode workspace opens (see Figure 3-3). This project contains all the files needed to design a new, universal application centered on a single primary window. The files are grouped together into folders and listed in the left-hand pane, which is called the Navigator. Your new project is selected by default. Its project and target settings appear in the right-hand editor pane. This project settings editor is functionally similar to the target info pane found in earlier Xcode releases but with many improved features. The first editor pane you see allows you to choose orientation support and set application images.
Figure 3-3. This brand-new Hello World project was created by choosing one of the available templates. On older projects, you may see a “modernize” button on this screen as well.
Feel free to explore the files in your new project. Open groups (they look like folders but are just organizing aids for your project) to expose their contents, and then select any file to view it in the editor. To expose all the folders at once, Option-click the arrow next to the main project listing (that is, “Hello World” in this case) when no subfiles are showing. If files are showing, Option-click twice. The first click hides all the subfiles; the second click reveals them.
Xcode 4’s editor supports code, property lists, images (display only), and Interface Builder (IB) files. If you click, for example, on MainWindow_iPad.xib, you will open an IB editor pane. That’s a big change from Xcode 3, where Interface Builder was a separate program.
As Figure 3-3 shows, Xcode’s GUI has undergone massive changes from its 3.x incarnations. Whether you are new to iOS development or transitioning from an earlier SDK, it’s well worth exploring the Xcode workspace and its components. From a more integrated single-window workspace to the migration of Interface Builder into the main Xcode application, a lot of new features are waiting for you in Xcode 4.
Introducing the Xcode Workspace
Although it is not clear from Figure 3-3, the standard Xcode Project window is composed of three primary sections. You can best see this by clicking the Utility button at the top-right of the window. This is the second button from the right, and looks like a white rectangle with a smaller darker rectangle to its right. It is part of a set of seven buttons grouped as three buttons (labeled “Editor”), then three buttons (labeled “View”), then one button (labeled “Organizer”). Go ahead and click it to reveal the Utility section to the right of the editor. You may want to resize the workspace after exposing the Utility section.
Figure 3-4 shows the expanded workspace. It consists of three areas and a toolbar. From left to right, those areas include the Navigator pane, which allows you to browse project components, the Editor pane in the center, which provides editors and viewers for your files, and the Utility area to the right, which offers inspectors and library access.
Figure 3-4. The Xcode workspace consists of several areas, as shown here.
An optional debugging pane appears at the bottom of the editor when a program runs. You can show and hide it by clicking the debugger disclosure button at the bottom-left of the editor or by clicking the center of the three view buttons at the top-right corner of the Xcode window. The disclosure button is a small rectangle with an upward (“show”) or downward (“hide”) triangle. The view button is a rectangle with a darker embedded rectangle at its bottom.
A small central activity view appears in the center of the toolbar at the top of the window. It has a light blue color and can be found just under the window’s title. This view shows you the current state of your project and any ongoing activities, such as building code or an ongoing search. It looks a lot like the activity view you see in iTunes. Application run, stop, and breakpoint controls can be found just to the left of the activity view.
Controlling the Workspace
The seven buttons at the right of the workspace toolbar allow you to select the ways you want to view your workspace. Starting from the left, these buttons are as follows.
- Editor buttons—These three editor buttons control how code is displayed in the central editor window. Your choices are standard, assistant, and version:
- The standard editor (Command-Return) displays a single source code pane.
- The assistant (Command-Option-Return) allows you to split your viewer in two, providing context-enhancing files in the secondary pane. The assistant can automatically find files and display file counterparts (for example, showing MyClass.h when viewing MyClass.m), superclass or subclass files, and so forth. The assistant is an absolutely brilliant feature of Xcode 4. Customize your assistant layout using the View > Assistant Layout submenu.
- The version editor (Command-Shift-Option-Return) allows you to compare two versions of a single file against each other, so you can spot differences and see what has changed over time between separate commits.
- View buttons—These three buttons allow you to hide and show the Navigator (left), Debug (center), and Utility (right) panes that appear in Figure 3-4. When all three are hidden, only the central editor pane appears. Doing so provides what appears to be a simple editor window but with quick access back to your project controls. You can also double-click files in the Navigator to open them up in new windows, with the other panes hidden.
- Organizer button—Looking like a small window with smaller embedded rectangles, the Organizer button provides one-click access to the Xcode Organizer window. The Organizer, which is discussed later in this chapter, provides a single source for your mobile device controls, documentation, project organization, and more. You can also access the organizer by choosing Window > Organizer, or by pressing Command-Shift-2 on the keyboard.
The left pane of the Xcode window doesn’t just list projects and folders. It handles a lot more as well. It’s called the “navigator area” and it lets you navigate information about projects in your workspace. Xcode 4 offers seven specialized navigators. Each navigator organizes information so you can browse through it. These navigators are accessed through the tab buttons at the top of the Navigator pane. Xcode 4 navigators include the following items:
- The Project Navigator (Command-1) lists the groups and files that comprise your project. Selecting a file opens that file in an editor in the central pane. The kind of editor presented depends on the selected file. A code file (.h, .m, and so on) opens a code editor. Property list files, such as your Info.plist, open a property list editor. Interface files (.storyboard and .xib files) open in an Interface Builder (IB) editor, directly in the Xcode project window. This differs from earlier versions of Xcode, where IB was a standalone program, outside of Xcode.
- The Symbol Navigator (Command-2) enumerates the classes, functions, and other symbols used within your project. Selecting a symbol opens the declaring header file, so you can instantly look up how the element is defined. The Utility > Symbols (Quick Help) inspector pane, found in the right-hand area on the other side of the editor, works synchronously with the Symbol Navigator by providing instant contextual documentation for any selected symbol, whether you select one from the Symbol Navigator or from the source editor.
- The Search Navigator (Command-3) provides an easy way to find text within your project. You can search both in your workspace (including any projects that have been added to the workspace) and in associated frameworks for instances of that text. Choose the search method you want to use from the text field pop-down as you type into the text field. A simple pop-up to the left of the search field lets you use find-and-replace features as well. You are not limited to searching via this Search Navigator. You can also search via Command-F (Edit > Find > ...) in any text-based editor.
- The Issue Navigator (Command-4) provides a list of warnings and errors found during your build requests. Use this pane to select each issue and highlight its problem in the central code editor.
- The Debug Navigator (Command-5) offers a way to examine threads and stacks during execution. When you select an item, the editor will instantly jump to either the source code or disassembly window, where you can see the current point of execution.
- The Breakpoint Navigator (Command-6) provides a global list of debugging breakpoints within your project. Click any breakpoint to view it in-file in the editor.
- The Log Navigator (Command-7) allows you to view your build results as a history. Click any past build to see the build log in the central editor pane.
Xcode Utility Panes
Context-specific helper panes appear in the right-hand utility pane. Like the left-hand navigator, the utility area can be shown or hidden as needed. This area consists of two sections: at the top is the Inspectors pane; at the bottom is the Libraries pane. Inspectors provide information about and options to customize a current selection. For example, when you select a label (a UILabel instance) in the embedded Interface Builder, you can set its alignment, background color, or dimensions using inspectors. Libraries offer pre-built components that you can incorporate into your project, and can include media and code snippets.
Both panes provide a set of tabbed subpanes in a similar fashion to the Navigator panes. Buttons appear at the top of each pane. Inspector buttons update to match the context of the current selection. For example, the object attributes and connections inspectors that appear for a UILabel object do not appear when working with text in a source code editor. That’s because those Interface Builder–style inspectors have no meaning when working with source code. The Utility pane updates to match the currently selected item in the central editor.
Inspector shortcuts are Command-Option combined with a number, starting with 1 and 2 for the File (Command-Option-1) and Quick Help (Command-Option-2) inspectors, respectively. They increase numerically from there, depending on the available inspector utility panes. Typically IB-style inspectors include Identity (Command-Option-3), Attributes (Command-Option-4), Size (Command-Option-5), and Connections (Command-Option-6). Xcode 3.x users should note that the pane orders have been switched around a bit from what was used in 3.x Interface Builder, plus the old keyboard shortcuts no longer apply.
Libraries use Command-Control-Option shortcuts combined with a number. The library pane provides access to file templates (Command-Control-Option-1), code snippets (Command-Control-Option-2), objects (Command-Control-Option-3), and media (Command-Control-Option-4). You can add your own custom elements into the code snippets libraries to provide easy access to repeated code patterns.
Hide or reveal the Utilities section by typing Command-Control-Option-0.
The Editor Window
The editor window includes a primary space, where content is displayed. Above this space, you’ll find a “jump bar.” This bar simplifies finding other files using any level of grouping. Each of the path-like elements provides a pop-up menu, offering quick access to those elements. Jump bars appear in many Xcode 4 roles. They all work similarly and introduce a hierarchical way to move around a structured system.
A special menu item, the small button with eight rectangles at the very left of the jump bar helps you find files related to the currently displayed item. Options include code counterparts (.m/.h file pairs), superclasses, subclasses, siblings, categories, included files, and more. This is a particularly powerful menu that you shouldn’t overlook.
The central space of the editor window offers Quick Look technology to provide previews of nearly any kind of content you will add to your Xcode projects or will need to use in support of that project. This means you can use the content viewer not only for direct coding material, but also to review PDFs and keynote presentations that relate to developing the project, for example.
Working with Multiple Editor Windows
You may want to work with several editor windows at once. To accomplish this, you can create a new workspace window, work in one window using tabs, or detach a floating editor. Both windows and tabs allow you to switch quickly between various editors and files.
To open new editor windows without taking an entire workspace with you, double-click any filename. A floating editor window appears above your workspace with the contents of that file.
To create a new workspace window, choose File > New > New Window (Command-Shift-T). The new window contains the same project or projects as the original workspace. Changes to a file in one window or tab are mirrored to the same file in other windows or tabs.
To use tabs, choose View > Show Tab Bar. This reveals a workspace tab bar between the main toolbar and the panes below it. Create new tabs using File > New Tab (Command-T) or right-click (Control-click) in the tab bar and choose New Tab from the contextual pop-up. Alternatively, press Shift-Option while clicking a filename in the navigator and click the + button at the top-right to open the file in a new tab.
Xcode tabs follow Apple’s standards, so if you’re used to using Safari tabs, they’ll work similarly in Xcode. To navigate between tabs from the keyboard use Command-Shift-[ to move left and Command-Shift-] to move right. Click + to add a new tab to your window. You can pull tabs out into their own windows and can drop tabs into existing windows by adding them to tab bars.
The Cocoa Samurai blog (cocoasamurai.blogspot.com) created a number of Xcode 4 keyboard shortcut reference guides. These infographics, which are hosted at github (github.com/Machx/Xcode-Keyboard-Shortcuts), provide an exhaustive guide to the key combinations you can use to navigate through Xcode.
Review the Project
When Xcode creates your new project, it populates it with all the basic elements and frameworks you need to build your first iOS application. Items you see in this project include the following:
- Frameworks > Foundation and Core Graphics frameworks—These essential frameworks enable you to build your iPhone applications and are similar to the ones found on OS X.
- Frameworks > UIKit framework—This framework provides iOS-specific user interface APIs and is key to developing applications that can be seen and interacted with on the iPhone screen.
- Products > HelloWorld.app—This placeholder is used to store your finished application. Like on the Macintosh, iPhone applications are bundles and consist of many items stored in a central folder.
- Supporting Files > HelloWorld-Info.plist—This file describes your application to the iPhone’s system and enables you to specify its executable, its application identifier, and other key features. It works in the same way Info.plist files work on the Mac. Localizable strings for the property list can be found in the Supporting Files > InfoPlist.strings file(s).
- MainStoryboard_iPhone.storyboard and MainStoryboard_iPad.storyboard—These Interface Builder files create a minimally populated GUI for each platform. You will modify these in the upcoming walkthrough.
- [Prefix]AppDelegate.h, [Prefix]AppDelegate.m, [Prefix]ViewController.h, [Prefix]ViewController.m, main.m—These files contain a rough Objective-C skeleton that you can customize and expand to create your application. The prefix used by these files is set in the new project options screen. Feel free to browse through the code, but you will not edit these files in the upcoming walkthrough. Instead, you use the way that Xcode set them up and limit your modifications to the Interface Builder storyboards.
Open the iPhone Storyboard
Locate the MainStoryboard_iPhone.storyboard file in the Project Navigator. Storyboards store Interface Builder layouts and can include all the screens (called “scenes”) for a single application. Select the storyboard file to open it in the central editor so you can begin to edit the file. You will see a grid pattern in the background of the editor and a scene list on the left side of the window. This list initially consists of the single Hello World View Controller Scene. The scene appears in the gridded area and consists of an empty view on top and an associated object dock beneath it. Figure 3-5 shows how this looks.
Figure 3-5. The Interface Builder window for an iPhone storyboard. A small dock floats below each storyboard scene, offering access to objects associated with its view.
The two icons in the dock represent elements of the interface you’re editing. On the right is the view’s owner—in this case, its view controller. It represents the view controllers attached to the view.
View controllers don’t have a visual presentation. They manage views, but they don’t display anything of their own. Each view controller has a property called “view” that is set to some UIView responsible for providing the actual onscreen presentation. Here, that view is displayed above the dock. You can see more about the controller by selecting it and opening View > Utilities > Show Identity Inspector. Observe the class listed in the inspector (ESViewController or similar).
The view controller element in the dock is called a “proxy.” A proxy plays a role in IB but the object that it represents (the view controller) is not itself embedded in the .storyboard archive. This proxy represents the object that loads and owns the view.
To see how items are connected to each other, choose View > Utilities > Show Connections Inspector. You see an outlet listed called “view.” Hover your mouse over this outlet and the view darkens. A small tooltip (saying “View”) appears as well. That’s because the view outlet for your view controller is already connected to that view. Outlet is IB-talk for “instance variable.”
The other icon, the one that appears in the left position of the dock, is called First Responder. It looks like a dark orange cube with the number 1 on it. Like the view controller, it’s a proxy object. It represents the onscreen object that is currently responding to user touches. During the lifetime of an application, the first responder changes as users interact with the screen. For example, imagine a form. As the user touches each text field in that form, that field becomes active and assumes the first responder role. At times you want to allow interface elements (such as buttons and switches) to control whatever item is the first responder. Connecting to this proxy in Interface Builder allows you to do so.
Edit the View
To start customizing, click the big white view. By default, this view is empty although it shows a status bar at the top. It’s up to you to customize this and add any content. To do so, you rely on two tools from the Utility area: the Interface Builder object library and the inspector.
Choose View > Utilities > Show Attributes Inspector (Command-Option-4). The Attributes Inspector lets you adjust the properties of the currently selected object—in this case, the view that you are editing. In the inspector, locate the View > Background Listing with its colored swatch. Click the swatch and choose a new color from the Colors palette. The view you are editing automatically updates its background color.
Next, open the object library by choosing the third icon at the top of the bottom pane. Alternatively, select View > Utilities > Show Object Library (Command-Control-Option-3). This library (see Figure 3-6) presents a list of prebuilt Cocoa Touch elements you can use in your IB files. These include both abstract elements such as view controllers as well as visual components such as buttons and sliders. Enter label in the search field at the bottom of the library. Drag the label from the middle pane and drop it onto your window. (Alternatively, double-click the label in the library. This automatically adds that item to your window.)
Figure 3-6. The Interface Builder object library.
Once it is dragged to the view, double-click the label and change the words from “Label” to “Hello World.” You can also move the label around in the window to appeal to your aesthetic sensibilities or set its location in the Size Inspector. The Attributes Inspector allows you to set the font face and size, as well as the text color. You may need to resize your label to accommodate the new size. Unselect “Autoshrink” and note that there are two places to set the font size. The field in the main inspector sets the minimum font size for the label. The pop-up for the font sets the desired font size.
Save your project with File > Save (Command-S). You have now customized your iPhone window with this content.
Next, customize the iPad interface. Return to the Project Navigator and select MainStoryboard_iPad.storyboard. You’ll notice that the iPad presentation is far larger than the iPhone one. You may not be able to see the entire iPad interface at once, even on relatively large screens.
Interface Builder allows you to double-click in the grid background to shrink the presentation to a more manageable size, but you cannot perform edits in this mode. You can also use the new zoom/shrink buttons at the bottom-right of the editor window. Many developers find it worth investing in a large vertical monitor rather than a horizontal one in order to better work with iPad edits in IB.
As before, change the view’s background color, add a label (“Hello World on iPad,” perhaps) and mess with its font and placement. Again, save your project (File > Save, Command-S).
Run Your Application
Locate the pop-up in the workspace toolbar just to the right of the Start/Stop buttons at the top-left of the window. From this pop-up choose Hello World > iPhone Simulator. This tells Xcode to compile your project for the Macintosh-based iPhone simulator. If more than one simulator choice presents, select the most recent SDK (that is, 5.3 rather than 5.0).
Click the run button (by default it looks like a “Play” button) or type Command-R and then wait as Xcode gets to work. It takes a few seconds to finish compiling, and then Xcode automatically launches the simulator, installs your project, and runs it. Figure 3-7 shows the result, the Hello World application running on the simulator.
Figure 3-7. The customized Hello World application runs on the simulator.
After testing the application on the iPhone simulator, click the stop button (to the right of the run button) and test the application using the iPad simulator. Select Hello World > iPad Simulator from the pop-up and again click the run button.