Working with the Source Editor - Building RoadTrip - iOS App Development For Dummies (2014)

iOS App Development For Dummies (2014)

Part II. Building RoadTrip

Chapter 7. Working with the Source Editor

In This Chapter

arrow Using the Standard source editor to add code

arrow Fixing syntax errors as you code

arrow Getting the help you need from the documentation and other forms of help

arrow Searching and finding symbols

You may be chomping at the bit to write code, but that's exactly what you've been doing ever since Chapter 2. (Chapter 1 was an introductory overview, as you may recall.) You've started building a storyboard for your app's interface — that was writing code just as much as typing print "Hello World" is. You've configured your project's settings with the graphical user interface tools of Xcode — that, too, is writing code.

But typing code into an editor is still a major part of the developer's work, and in this chapter, you'll look at the source code editing features of Xcode.

In this chapter, I tell you how to navigate the files in your project using the Jump bar and the navigators, as well as how to work with the source editor to enter code. And for when you are confused, or simply just curious, I explain how to access the documentation and Xcode’s Help system. This chapter finishes the explanation on how to use Xcode.

Navigating in the Xcode Source Editors

In previous chapters, I give you quite a bit of information about the Xcode Workspace, albeit primarily focusing on storyboards. I mention the Assistant as well, and in this chapter, I want to extend that knowledge and describe most of the rest of the tasks you need to be able to do in Xcode.

As you’ve seen, most development work in Xcode is done in the Editor area, the main area that's always visible within the Workspace window. The Editor area can also be further configured, with the Standard editor pane always shown, as well as one or more optional Assistant panes that show related content. (If you select an interface [.h] header file, the Assistant pane can automatically show the corresponding implementation [.m] code file, and vice versa; I don’t talk about the Version pane, but showing that area is also an option.) I use the term pane (Standard editorpane and Assistant pane) to refer to certain configurations. I do this to distinguish between the Editor area configuration (the Standard editor isn't actually an editor at all, but simply a single pane configuration in the editor area) and the built-in editors — an editor operates in an Editor area. The main editors are the following:

· Source editor: You use this editor to write and edit your source code, as well as to set and enable (or disable, for that matter) breakpoints as well as to control program execution.

· Project editor: With this editor, you view and edit project and target settings, such as build options, target architectures, and code signing characteristics.

· Core Data Model editor: If you use Core Data, you can design your data model for tables and relationships graphically. The Core Data Model editor also can convert your graphical representation of your data model to Objective-C code. Core Data is outside the scope of this book, but the Core Data model editor is definitely worth exploring.

· Interface Builder: Here, you graphically create and edit user interface files in storyboards and .xib files.

The editor you use is determined by what you have selected in the Project navigator. An editor pane appears for that (selected) item in the Editor area.

So far, you’ve worked primarily in the Interface Builder editor, but when you code, you do the bulk of your work in the source editor in the Standard editor pane, with some forays, as needed, in the Assistant editor pane and an occasional excursion into the Utility area as well.

As described earlier in the book, you use the View selector in the Workspace toolbar to hide or show the Navigator, Debug, and Utility areas. (To review the Xcode workspace landscape, see Chapter 2.) If you like, you can hide the other areas and see just the source editor (and perhaps the Assistant).

image Figure 7-1 shows the Project navigator. Because I selected MasterViewController.m, you see the source editor displaying that file in the Standard editor pane. (If you were to select one of the storyboard files in the Project navigator, you’d see Interface Builder as your editor of choice; that’s the editor I highlight in Chapter 5.) In Figure 7-1, I also selected the Assistant in the Editor selector and split the panes using the split controls (“+” icon at the far right in the Jump bar).

image

Figure 7-1: The source editor with Standard and Assistant editor panes.

image Notice that when I selected the Assistant, the MasterViewController.h file opened. That’s because the Assistant editor pane automatically (depending how you have set it — see the next section) shows the related content for whatever I select in the Project navigator so that you can edit both easily. You then see MasterViewController.m (the implementation code file) in the Standard source editor pane and MasterViewController.h (the header file) in the Assistant editor pane. Clicking the split control (the + at the right of the jump bar) opens a second pane in the Assistant editor pane as well, giving you a total of three panes.

The Standard editor pane (the left editor pane, or the top one if you have a horizontal split) is the one that’s affected by changing your selection in the Project navigator.

image The interface (.h) header file defines the class’s interface by specifying the following:

· The class declaration (and what it inherits from)

· Methods

· Any instance variables (that is, variables defined in a class)

· Declared properties

image In recent updates to Xcode and the sample code on developer.apple.com, Apple has rejiggered the world of variables and properties with regard to classes. Declared properties are preferred to instance variables because they can contain more information than just the type and name of a variable and because their accessors can further encapsulate the data. However, instance variables rather than properties are often more appropriate for scalars such as ints and floats. In addition, declaring instance variables as well as properties in a class extension in the implementation file further keeps them out of the way so that they are not visible to other classes.

The implementation (.m) code file, on the other hand, contains the code for the class, which includes each method definition. It also can contain a class extension with instance variable and property declarations. See Chapter 6 for more on this topic.

image By default, the Assistant editor pane appears to the right of the source editor pane. To change the orientation of the Assistant editor pane to the source editor pane, choose View⇒Assistant Editor and then choose a layout. If the header file doesn’t appear for you, navigate to it using the Jump bar, as explained in the next section.

Using the Jump bar

A Jump bar appears at the top of each Editor area pane to provide an alternative way to navigate through the files and symbols in your project. You can use the Jump bar to go directly to items at any level in the Workspace.

A Jump bar is an interactive, hierarchical mechanism for browsing items in your workspace. Each editor area includes a Jump bar, as do Interface Builder and the documentation organizer. The configuration and behavior of each Jump bar is customized for the context in which it appears.

image The active pane is indicated by slightly darker arrows in the Jump bar. Experiment for yourself and you’ll soon notice the difference. It’s subtle enough that it’s not easy to distinguish on the screenshots in this book.

The Standard editor Jump bar

The Standard editor Jump bar has the basic configuration, which includes the following:

· image Context-related items: Click the Related Items menu (represented by an icon showing a cluster of tiny rectangles on the far left side) to see additional selections relevant to the current context, such as recently opened files or the interface (.h) header file for an implementation (.m) code file you're editing.

· image Previous and Next buttons: These are the left- and right-arrow buttons on the left side of the Jump bar. You use these to step back and forth through your navigation history just as you would with a web browser.

· A hierarchical path menu: This menu shows the same structure that you see in the Project navigator, down to individual files and the symbols inside the files. The path you would see in the source editor in the Standard editor pane is shown in Figure 7-2.

The hierarchical path menu lets you quickly choose a file. For example, in Figure 7-3, I get an overview of all the RoadTrip files when I select the RoadTrip project in the hierarchical path menu.

Selecting the last item in the hierarchical path menu provides a list of all the symbols in that file, as shown in Figure 7-4.

image

Figure 7-2: The hierarchal path menu in the Standard editor pane.

image

Figure 7-3: A file hierarchy.

image

Figure 7-4: A tour of MasterViewController.m.

The Assistant modes and the Jump bar

When you use the Assistant, you’ll find that the Jump bar differs somewhat from the Jump bar of the Standard editor. The Assistant’s Jump bar has two modes: Tracking (or Automatic) mode and Manual mode:

· Manual mode: You select the file to display in the Assistant pane on your own, rather than have the Assistant choose for you. (As mentioned previously, you can also split the Assistant editor pane to create multiple assistant editors.)

· Tracking mode: As you can see in Figure 7-5, you can automatically see the counterpart files (.h files for .m files and vice versa), the interface files, and other related files. This can be a great time-saver because most of the files you are probably looking for are only a click away.

image Hold down the Option key when selecting an item in the Project navigator to open the Assistant and display that item in the Assistant editor pane.

If you have any questions about what something does, just position the mouse pointer above the icon; a tooltip appears to explain it.

image

Figure 7-5: Assistant options in the source editor.

Organizing your code using the #pragma mark statement

While you’re here, this is a good time to introduce the #pragma mark statement. If you look in DetailViewController.m, you can see how this statement can be used to group things in your file; such statements are also displayed in the list of symbols.

You use the # pragma mark statement with a label (such as View life cycle or Animation) to add a category header in the Methods list so that you can identify and keep separate the methods that fit logically in the list.

For example, in the DetailViewController template, I added

#pragma mark - Managing the detail item

The first part of the statement (with a space and a dash) places a horizontal line in the Methods list. The second one places the text “Managing the detail item” in the Methods list.

This is a useful trick for finding code sections, organizing your code, and adding new code in the proper sections.

image Some sections for your code are easy to identify, but, as you’ll see in some of the sample code on http://developer.apple.com, developers differ as to how they organize their code. Should viewDidLoad go in a section called User Interface or Initialization? Do whatever makes the most sense to you. It’s probably a good idea to stick with the code sections in the templates and sample code at least to start.

Using the Xcode Source Editor

The main tool you use to write code for an iOS app is the Xcode source editor, which appears as the Standard editor pane in the editor area on the right side of the Xcode Workspace window after you select a source code file in the Project navigator. It also appears as the Assistant editor in a second pane if you click the Assistant Editor button — the middle Editor selector button in the top-right corner of the Workspace window.

Apple has gone out of its way to make the source editor as useful as possible by including the following:

· Code completion: Code completion is a feature of the editor that shows symbols — arguments, placeholders, and suggested code — as you type statements. Code completion can be really useful, especially if you’re like me and forget exactly what the arguments are for a function. When code completion is active (as it is by default), Xcode uses the text you typed — as well as the context within which you typed it — to provide inline suggestions for completing what it thinks you’re going to type. You can accept inline suggestions by pressing Tab or Return. You can also see a pop-up list of suggestions while typing; move up and down the list with the up and down arrows. Press Return to use the selected completion. Press the Esc key, or Control+spacebar, to cancel a code completion operation. You can turn off code completion, or set options for code completion, by choosing Xcode⇒Preferences and clicking the Text Editing tab.

· Automatic indenting, formatting, and closing braces: As I explain in Chapter 3 in the section on preferences, the source editor indents the text you type according to rules you can set in the Text Editing preferences pane. It also uses fonts and colors for the various syntax elements (variables, constants, comments, and so on) according to the settings in the Fonts & Colors pane of Xcode preferences. As for closing braces, anytime you type an opening brace ({) and then press Return, Xcode automatically adds a closing brace (}) — unless you’ve deactivated the Automatically Insert Closing “}” option in the Text Editing preferences.

· Code folding in the Focus ribbon: With code folding, you can collapse code that you’re not working on and display only the code that requires your attention. You do this by clicking in the Focus ribbon column (see Figure 7-6) to the left of the code you want to hide (between the gutter, which can display line numbers and breakpoints, and the editor). A disclosure triangle appears, and clicking it hides or shows blocks of code. Notice that in Figure 7-6, the code inside awakeFromNib has been folded up.

· Opening a file in a separate window: Double-click the file in the Project navigator to open the file in its own window.

image

Figure 7-6: The Gutter and Focus ribbon.

Using Live Issues and Fix-it

The Apple LLVM compiler engine wants to be your best friend, so Live Issues continuously evaluates your code in the background and alerts you to coding mistakes. Before this feature came along, you had to build your app first, and trust me, this new way saves lots of time and effort.

But not only is Live Issues happy to point out your mistakes (like someone else I know, but I won’t go there), Fix-it will also offer (when it can) to fix the problem for you. Clicking the error displays the available Fix-its, such as correcting an assignment to a comparison, repairing a misspelled symbol, or appending a missing semicolon. With a single keyboard shortcut, you can instantly have the error repaired, and you can continue coding. Fix-it marks syntax errors with a red underline or a caret at the position of the error and with a symbol in the gutter.

For example, in Figure 7-7, the semicolon is missing after the [super viewDidLoad] statement. (Notice the error indicator — the red stop sign with exclamation point — in the Activity viewer along with the red circle in the gutter at the left of the offending line of code.) Clicking the red circle in the gutter at the left will automatically fix this problem. This is a very useful feature and will cut down your debugging time significantly (especially if you actually use it).

image

Figure 7-7: Live Issues and Fix-it.

Compiler warnings

Although Xcode and the compiler working together are very good at giving you warnings and errors, sometimes they're a little slow on the uptake when you actually get around to fixing the problem. So don’t be surprised by random warnings and errors, especially if the compiler for some reason can’t find the header file.

If you see a warning or error that you’re just sure you’ve fixed, you can click the Run button. Xcode and the compiler will reset, and the warning will go away. (Unless, of course, it was right all along and you hadn’t fixed the problem.)

The Issue navigator

image The Issue navigator is one of the navigators provided by Xcode. The error displayed in Figure 7-7, shown previously, also appears in the Issue navigator, as shown in Figure 7-8.

image

Figure 7-8: An error message displayed by the Issue navigator.

image To get to the Issue navigator, you select it in the Navigator selector bar.

If, in spite of Live Issues and Fix-it (or any other) warnings, you decide to compile the program, the Issue navigator will automatically launch for you.

The Issue navigator displays the error and warning messages generated in a Project or Workspace and is similar to the other navigators you've used so far.

When you select a warning or error in the Issue navigator, an editor displays the item with the issue, and if the error occurs in a source file, the issue message is placed on the line of code with the issue.

image Place the pointer over an issue message that ends with an ellipsis (which appears if the pane is too narrow to display the entire message) to get a complete description of the issue.

You can display issues by file or by type using the buttons on the Scope bar at the bottom of the navigator pane (refer to Figure 7-7), filter the issue list with the Filter bar, and even step through issues using the Issue stepper in the Jump bar. Use the Next and Previous buttons in the Jump bar to jump to the previous and next issues.

As you may recall from Chapter 3, I changed Xcode preferences to have the Issue navigator displayed and a sound played when a build fails.

Accessing Documentation

The ability to quickly access documentation is a major feature of Xcode, and one you’ll want to use regularly. If you have no idea how to do something, or how something works, you can often find the answer in the documentation.

Being able to figure out what's going on will make your life easier. You saw that Xcode will complete your code for you, which is useful when you can’t quite remember the method signature and parameters, but what if you don’t even have a clue?

Or like many developers, you may find yourself wanting to dig deeper when it comes to a particular bit of code. That’s when you’ll really appreciate things like Xcode’s Quick Help, the Documentation and API Reference pane in the Help menu, and the Find tools. With these tools, you can quickly access the documentation for a particular class, method, or property.

Getting Xcode help

To see how easy it is to access the documentation, say that you’ve selected MasterViewController.m. What if you wanted to find out more about UITableViewController, the super class of MasterViewController?

image The Quick Help section of the Utility area provides documentation for a single symbol. (To see the Utility area, click the rightmost View selector button in the top-right corner of the Workspace window and select the second button in the Inspector selector bar.) In an editor, click anywhere in the symbol or select the entire symbol, as shown in Figure 7-9.

The Quick Help section of the Utility area shows a description of the symbol and provides links to more information. For example, you can click the UITableViewController Class Reference link near the bottom of the Quick Help section (refer to Figure 7-9) to bring up the class reference definition in a Documentation window, as shown in Figure 7-10. I use class references a lot!

image

Figure 7-9: Accessing the Quick Help section of the Utility area.

image

Figure 7-10: The class reference in a Documentation window.

With the Quick Help section open, information is available for three types of elements in your project, depending on your selection in the open editor:

· Symbols, in the source editor

· Interface objects, in Interface Builder

· Build settings, in the Project editor

It may be more convenient to use a Quick Help window if, for example, you prefer to work with the Utility area hidden. To do so, press Option and click Symbols in the source editor.

As you can see in Figure 7-11, a Quick Help window appears with the pointer indicating the item you selected (in this case, the symbol UITableViewController):

image If you’re like me and want to go directly to the class reference, press Option and double-click the symbol instead.

image

Figure 7-11: The Quick Help window.

The Organizer window

You can have only one Organizer window (shown in Figure 7-12). You use the organizers in this window to manage the development resources such as devices (for testing), projects, and archives.

To display the Organizer window, choose Organizer from the Window menu. The window includes three individual organizers, whose tasks I describe in the following list:

· Devices organizer: Lets you provision a device, manage your developer profile, install iOS on the device, and work with your app and its data. This organizer is present only if the iOS SDK is installed.

· Projects organizer: Lets you find, view, and manage an open project or Workspace, its derived data, and its snapshots. Note that a project organizer lets you managed derived data — that consists of data that doesn’t have to be recompiled each time. The Delete button lets you delete a set of derived data. It’s a bit like a “Super Clean” button to force everything to be recompiled.

· Archives organizer: Lets you view and manage build product archives resulting from your distribution scheme.

image

Figure 7-12: The Organizer window.

Each of these organizers includes task-oriented contextual help articles that you can view by choosing the Organizer and clicking in its content pane while pressing Control.

I explain a bit more about some of the other organizers as you use them in upcoming chapters.

The Help menu

The Help menu’s search field (in the Xcode menu bar) also lets you search Xcode Help, the Xcode User Guide, and Documentation and API Reference. You can also choose Quick Help for Selected Item, which displays a Quick Help panel above the selected symbol in the editor.

Finding and Searching in Your Project

You’ll find that, as your classes get bigger, sometimes you’ll want to find a symbol or some other text in your project. Xcode provides a number of ways to do that.

Using the Find command to locate an item in a file

Need to track down a single symbol or all occurrences of a symbol in a file or class? You can easily locate what you’re looking for by using the Find menu or pressing image+F, which opens a Find toolbar above the Editor pane to help you search the file in the editor.

image The Find menu has 15 find-and-replace submenus. The keyboard equivalent image+F opens a find-and-replace bar above the Editor pane. They are not the same.

For example, as shown in Figure 7-13, I entered viewDidLoad in the Find toolbar. Xcode found two instances of viewDidLoad in the source editor and highlighted them. (Admittedly, the first highlight is a tad darker.)

image

Figure 7-13: You can use Find to locate something in a file.

image You can jump from one instance to the next by pressing image+G. Or you can use the Previous and Next buttons (left and right arrows) on the Find bar.

Click the Find pop-up menu on Find toolbar and choose Replace to do a file-level replace.

Click the magnifying glass in the Search field in the Find toolbar to display a menu that allows you to show or hide the Find options. For example, you can choose to ignore or match the case of the text in the Search field. Changes you make to this set of options remain persistent for future searches.

Using the Search navigator to search your project or framework

image Whereas the Find command works for locating an item in a file or class, you use the Find navigator (the third button from the left in the Navigator selector) to find items in your project or even frameworks. You can use Shift+Command+F as a handy keyboard shortcut for the Find command in the Workspace menu item, which also opens the Find navigator pane.

In Figure 7-14, I entered viewDidLoad in the Find field. I also clicked the magnifying glass in the Find field to display search options. (Clicking in the Find pop-up menu will also let you choose Replace to perform a global replace.)

image

Figure 7-14: The Search navigator shows a specific use of the search term in the file.

Note how the initial results of my search are displayed in the Find navigator; if I wanted to filter the Results list still further, I could enter text into the field at the bottom of the pane. Any items that don't match the text are removed from the Results list.

To go directly to where the search term appears in a file, click an entry under the file’s name in the Find navigator, as shown in Figure 7-14. The file appears in the editor pane on the right, open to the location where the search term appears.

Using the Symbol navigator

image The Symbol navigator allows you to browse through the symbols in your project — just click the Symbol button on the Navigator selector bar. Note that you need to wait until Xcode finishes indexing your project before you can use this feature.

You can display symbols in a hierarchical or flat list using the buttons at the top of the Symbol navigator.

You can specify which symbols are displayed by using the buttons at the bottom of the navigator. Buttons are blue when on and black when off. Use the following buttons in any combination:

· The first button on the Symbol navigator shows only class symbols and hides global symbol types.

· The middle button shows only symbols in this project.

· The third button shows only containers (classes and categories).

You can refine the Results list still more by entering text in the Filter field at the bottom of the navigator.

If you select a symbol to display, its header file definition will be displayed in the source editor. In Figure 7-15, I've hidden everything but the member symbols. In the resulting list, I then filtered on the viewDidLoad method, and its declaration in the header file was highlighted in the source editor.

image

Figure 7-15: The Symbol navigator.

You’re Finally Ready to Write Code!

Yes, it’s finally time to write code, and from here on, it’s full-steam ahead.