Documentation - IDE - iOS 8 Programming Fundamentals with Swift: Swift, Xcode, and Cocoa Basics (2015)

iOS 8 Programming Fundamentals with Swift: Swift, Xcode, and Cocoa Basics (2015)

Part II. IDE

Chapter 8. Documentation

Knowledge is of two kinds. We know a subject ourselves, or we know where we can find information upon it.

—Samuel Johnson, Boswell’s Life of Johnson

No aspect of iOS programming is more important than a fluid and nimble relationship with the documentation. There is a huge number of built-in Cocoa classes, with many methods and properties and other details. Apple’s documentation, whatever its flaws, is the definitive official word on how you can expect Cocoa to behave, and on the contractual rules incumbent upon you in working with this massive framework whose inner workings you cannot see directly.

The Xcode documentation installed on your machine comes in large chunks called documentation sets (or doc sets, also called libraries). You do not merely install a doc set; you subscribe to it, so that when Apple releases a documentation update, you can obtain the updated version.

When you first install Xcode, the bulk of the documentation is not installed on your machine; viewing the documentation in the documentation window (discussed in the next section) may require an Internet connection, so that you can see the online docs at Apple’s site. This situation is untenable; you’re going to want a copy of the documentation locally, on your own machine.

Therefore, you should start up Xcode immediately after installation to let it download and install your initial doc sets. The process can be controlled and monitored, to some extent, in the Downloads pane of the Preferences window (under Documentation); you can also specify here whether you want updates installed automatically or whether you want to click Check and Install Now manually from time to time. This is also where you specify which doc sets you want; I believe that the iOS 8 doc set and the Xcode 6 doc set are all you need for iOS development, but it can’t hurt to install the OS X 10.10 doc set as well. You may have to provide your machine’s admin password when a doc set is first installed. Doc sets are installed in your home Library/Developer/Shared/Documentation/DocSets directory.

The Documentation Window

Your primary access to the documentation is in Xcode, through the documentation window (Window → Documentation and API Reference, or Help → Documentation and API Reference, Command-Shift-0). Within the documentation window, the primary way into the documentation is to do a search; for example, press Command-Shift-0 (or Command-L if you’re already in the documentation window), type NSString, and press Return to select the top hit, which is the NSString Class Reference. Click the magnifying glass icon to limit the results to the iOS-related doc sets if desired.

There are two ways to see the results of a search in the documentation window:

Pop-up results window

If you’re actively typing in the search field, a dozen or so primary results are listed in a pop-up window. Click with the mouse, or navigate with arrow keys and press Return, to specify which result you want to view. You can also summon and hide this pop-up window by pressing Esc whenever the search field has focus.

Full results page

When the search field has focus and the pop-up results window is not showing, press Return to see a page listing all results of the search; these results are listed on four separate pages, by category: API Reference, SDK Guides, Tools Guides, and Sample Code.

You can also perform a documentation window search starting from within your code. You’ll very often want to do this: you’re looking directly at a symbol (a class name, a method name, a property name, and so on) at its point of use in your code, and you want to know more about it. Hold Option and hover the mouse over a term in your code until a blue dotted underline appears; then (still holding Option) double-click the term. The documentation window opens, and you are taken directly to the explanation of that term within its class documentation page. (Similarly, during code completion — discussed in Chapter 9 — you can click the More link to make this same move, jumping directly to the documentation on the current symbol.)

Alternatively, you can select text in your code (or anywhere else) and choose Help → Search Documentation for Selected Text (Command-Option-Control-/). This is the equivalent of typing that text into the search field in the documentation window and asking to see the full results page.

The documentation window behaves basically as a glorified web browser, because the documentation consists essentially of web pages. Multiple pages can appear simultaneously as tabs in the documentation window. To navigate to a new tab, hold Command as you navigate — for example, Command-click a link, or Command-click your choice in the pop-up results window — or choose Open Link in New Tab from the contextual menu. You can navigate between tabs (Window → Show Next Tab), and each tab remembers its navigation history (Navigate → Go Back, or use the Back button in the window toolbar, which is also a pop-up menu).

A documentation page may be accompanied by a list of related items. The start of the list is shown in a pane above the page; the full list appears in a popover when you click the “More related items” link (Figure 8-1). For example, the related items pane for the NSString Class Reference page includes links to NSString’s class inheritance and its adopted protocols, with further information and links in the popover. I’ll talk more about a class’s related items later in this chapter.

A documentation page may be accompanied by a table of contents, displayed in a pane to the left of the documentation page (Figure 8-1); to see it if it isn’t showing, choose Editor → Show Table of Contents, or click the Table of Contents icon in the window toolbar. For example, the NSString Class Reference page has a table of contents pane linking to all the topics and methods listed within the page. Some documentation pages may use the table of contents to show the page’s place within a larger group of pages; for example, the String Programming Guide consists of multiple pages, and when you’re viewing one, the Table of Contents pane lists all the pages of the String Programming Guide along with each page’s main topics.

A full hierarchical table of contents for all doc sets (the library) appears at the far left of the documentation window; to see it if it isn’t showing, choose Editor → Show Library, or click the Navigator button in the window toolbar. The hierarchy shows all reference documents, along with guides and sample code, clumped together by subject. When viewing a documentation page, to show it in its place within the full hierarchical table of contents, choose Editor → Reveal in Library (or choose Reveal in Library from the contextual menu).

When you encounter a documentation page to which you’re likely to want to return, make it a bookmark: choose Editor → Share → Add Bookmark, or click the Share button in the toolbar and choose Add Bookmark, or choose Add Bookmark from the contextual menu, or (easiest of all) click the bookmark icon in the left margin of the documentation page. Bookmarks are displayed at the left of the documentation window, sharing space in the navigator with the full hierarchical table of contents; to see the bookmarks pane if it isn’t showing, choose Editor → Show Bookmarks. Icons at the top of the navigator let you switch between the library pane and the bookmarks pane. Click a bookmark in the bookmarks pane to jump to it in the documentation window. Bookmark management is simple but effective: you can rearrange bookmarks or delete a bookmark, and that’s all.

To search for text within the current documentation page, use the Find menu commands. Find → Find (Command-F) summons a find bar, as in Safari.

TIP

A third-party documentation viewer application, such as Dash (http://kapeli.com/dash), may provide better searchability and a better view of your local doc sets than the documentation window does. Also, most of the documentation can be accessed using a real web browser at http://developer.apple.com, Apple’s developer site; this web browser display allows sections to be shown and hidden, it includes an alphabetic searchable index of methods and properties, and it may even show information that the documentation window omits.

Class Documentation Pages

In the vast majority of cases, your target documentation page will be the documentation for a class. It’s important to be comfortable and conversant with the typical features and information provided by a class documentation page, so let’s pause to notice them (Figure 8-1).

The start of the UIButton class documentation page

Figure 8-1. The start of the UIButton class documentation page

It’s important to keep an eye on the related items information when you’re studying a class (click the “More related items” link to see it):

Inherits from

Lists, and links to, the chain of superclasses. One of the biggest beginner mistakes is failing to consult the documentation up the superclass chain. A class inherits from its superclasses, so the functionality or information you’re looking for may be in a superclass. You won’t find out aboutaddTarget:action:forControlEvents: from the UIButton class page; that information is in the UIControl class page. You won’t find out that a UIButton has a frame property from the UIButton class page; that information is in the UIView class page.

Conforms to

Lists, and links to, the protocols adopted by this class. Failing to consult the documentation for adopted protocols is a serious beginner mistake. For example, you won’t find out that UIViewController gets a viewWillTransitionToSize:withTransitionCoordinator: event by looking at the UIViewController class documentation page: you have to look in the documentation for the UIContentContainer protocol, which UIViewController adopts.

Framework

Tells what framework this class is part of. Your code must link to this framework, and import this framework’s header, in order to use this class; in Swift, it will typically be sufficient to import the framework by its module name (see Chapter 6).

Availability

States the earliest version of the operating system where this class is implemented. For example, UIAlertController wasn’t invented until iOS 8. So if you want to use this feature in your app, you must make sure either that your app targets only iOS 8 or later, or that your code never uses this class when your app is running on an earlier system.

Declared in

The header(s) where this class is declared. Unfortunately this is not a link; I have not found any quick way to view a header starting from the documentation. That’s a pity, as it can often be worth looking at the header file, which may contain helpful comments or other details. You can open the header file from the project window, as explained later in this chapter.

Related documents

If a class documentation page lists a related guide, you might want to click that link and read that guide. For example, the UIView class documentation page lists (and links to) the View Programming Guide for iOS. Guides are broad surveys of a topic; they provide important information (including, often, useful code examples), and they can serve to orient your thinking and make you aware of your options.

Sample code

If a class documentation page links to sample code, you might want to examine that code. (But see my remarks on sample code in the next section of this chapter.)

The body of the class documentation page is divided into sections, which are listed in the table of contents pane:

Overview

Some class pages provide extremely important introductory information in the Overview section, including links to related guides and further information. (See the UIView class documentation page for an example.)

Tasks

This section lists, clumped into categories, the properties and methods of this class.

Constants

Many classes define constants that accompany particular methods. For example, to create a UIButton instance in code, you can call the buttonWithType: class method; the argument value will be a constant, listed under UIButtonType in the Constants section. (To help you get there, there’s a link from the buttonWithType: method to the UIButtonType section in Constants.)

Finally, let’s talk about how a class documentation page lists and explains individual properties and methods. In recent years, this part of the documentation has become quite splendid, with good hyperlinks. Note the following subsections, after the property or method name:

Description

A short summary of what the property or method does.

Formal declaration

Read this to learn things like the method’s parameters and return type.

Parameters and Return Value

Precise information on the meaning and purpose of these.

Discussion

Often contains extremely important further details about how this method behaves. Always pay attention to this section!

Import Statement

Shows the module that must be imported to access this method or property.

Availability

An old class can acquire new methods as the operating system advances; if a newer method is crucial to your app, you might want to exclude your app from running on older operating systems that don’t implement the method.

See Also

Links to related methods and properties. Very helpful for giving you a larger perspective on how this method fits into the overall behavior of this class.

WARNING

Methods injected into a class by a category (Chapter 10) are often not listed on that class’s documentation page and can be very difficult to discover. For example, awakeFromNib (discussed in Chapter 7) isn’t mentioned in the documentation for UIButton or for any of its superclasses or protocols. This is a major weakness in Apple’s organization and display of the documentation.

Sample Code

Apple provides plenty of sample code projects. You can view the code directly in the documentation window; sometimes this will be sufficient, but you can see only one file at a time, so it’s difficult to get an overview. The alternative is to open the sample code project in Xcode; click the Open Project link at the top of a sample code page in the documentation window. If you’re looking at the sample code in your browser at http://developer.apple.com, there’s a Download Sample Code button. With the sample code project open as a project window, you can read the code, navigate it, edit it, and of course run the project.

As a form of documentation, sample code is both good and bad. It can be a superb source of working code that you can often copy and paste and use with very little alteration in your own projects. It is usually heavily commented, because the Apple folks are aware, as they write the code, that it is intended for instructional purposes. Sample code also illustrates concepts that users have difficulty extracting from the documentation. (Users who have not grasped UITouch handling, for instance, often find that the lightbulb goes on when they discover the MoveMe example.) But the logic of a project is often spread over multiple files, and nothing is more difficult to understand than someone else’s code (except, perhaps, your own code). Moreover, what learners most need is not the fait accompli of a fully written project but the reasoning process that constructed the project, which no amount of commentary can provide.

My own assessment is that Apple’s sample code is uneven. Some of it is a bit careless or even faulty, while some of it is astoundingly well-written. It is generally thoughtful and instructive, though, and is definitely a major component of the documentation; it deserves more appreciation and usage than it seems to get. But it is most useful, I think, after you’ve reached a certain level of competence and comfort.

Quick Help

Quick Help is a condensed rendering of the documentation on some single topic, usually a symbol name (a class or method). It appears with regard to the current selection or insertion point automatically in the Quick Help inspector (Command-Option-2) if the inspector is showing. Thus, for example, if you’re editing code and the insertion point or selection is within the term CGPointMake, documentation for CGPointMake appears in the Quick Help inspector if it is visible.

Quick Help is also available in the Quick Help inspector for interface objects selected in the nib editor, for build settings while editing a project or target, and so forth.

Quick Help documentation can also be displayed as a popover window, without the Quick Help inspector. Select a term and choose Help → Quick Help for Selected Item (Command-Control-Shift-?). Alternatively, hold down Option and hover the mouse over a term until the cursor becomes a question mark (and the term turns blue with a dashed underline); then Option-click the term.

TIP

When you’re developing Swift code, Quick Help is of increased importance. If you click in the name of a Swift variable whose type is inferred, Quick Help shows the inferred type (see Figure 3-1). This can help you understand compile errors and other surprises.

The Quick Help documentation contains links. For example, click the Reference link to open the full documentation in the documentation window; click the header link to open the appropriate header file.

You can inject documentation for your own Swift code into Quick Help. To do so, precede a declaration with a comment enclosed in /**...*/. The comment becomes the Description field for Quick Help. Within the comment, some paragraph formatting can be used, and some additional fields can be specified, but unfortunately the syntax has not been formally documented, so you have to use guesswork and trial-and-error; it appears to be a form of reStructuredText (see http://docutils.sourceforge.net/docs/user/rst/quickref.html).

For example, here’s a function declaration with a preceding comment:

/**

Many people would like to dog their cats. So it is perfectly

reasonable to supply a convenience method to do so:

* Because it's cool.

* Because it's there.

:param: cats A string containing cats

:returns: A string containing dogs

*/

func dogMyCats(cats:String) -> String {

return "Dogs"

}

The double asterisk in the opening comment delimiter denotes that this is documentation, and the comment’s location automatically associates it with the dogMyCats method whose definition follows. The asterisked paragraphs will become bulleted paragraphs; the colon-delimited expressions :param: and :returns: correspond to additional Quick Help fields. The outcome is that when dogMyCats is selected anywhere in my code, its documentation is displayed in Quick Help (Figure 8-2). The first part of the description is also displayed as part of code completion (see Chapter 9).

Custom documentation injected into Quick Help

Figure 8-2. Custom documentation injected into Quick Help

Symbols

A symbol is a declared term, such as the name of a function, object type, or variable. If you can see the name of a symbol in your code in an editor in Xcode, you can jump quickly to the declaration of the symbol. Select text and choose Navigate → Jump to Definition (Command-Control-J). Alternatively, hold down Command and hover the mouse over a prospective term, until the cursor becomes a pointing finger (and the term becomes blue with a solid underline); Command-click the term to jump to the declaration for that symbol. When you do:

§ If the symbol is declared in your code, you jump to that declaration in your code; this can be helpful not only for understanding your code but also for navigating it.

§ If the symbol is declared in a framework, you jump to the declaration in the header file. If you started in a .swift file, the header file that you jump to is translated into Swift. (I’ll talk more about header files in the next section.)

The precise meaning of the notion “jump” depends upon the modifier keys you use in addition to the Command key, and on your settings in the Navigation pane of Xcode’s preferences. By default, Command-click jumps in the same editor, Command-Option-click jumps in an assistant pane, and Command-double-click jumps in a new window. Similarly, Command-Option-Control-J jumps in an assistant pane to the declaration of the selected term.

Another way to see a list of your project’s symbols, and to navigate to a symbol declaration, is through the Symbol navigator (Chapter 6). If the second icon in the filter bar is highlighted, these are symbols declared in your project; if not, symbols from imported frameworks are listed as well.

To jump to the declaration of a symbol whose name you know, even if you don’t see the name in the code before you, choose File → Open Quickly (Command-Shift-O). In the search field, type key letters from the name, which will be interpreted intelligently; for example, to search forapplication:didFinishLaunchingWithOptions:, you might type appdidf. Possible matches are shown in a scrolling list below the search field; you can navigate this list with the mouse or by keyboard alone. Besides declarations from the framework headers, declarations in your own code are listed as well, so this, too, can be a rapid way of navigating your code.

Header Files

Often, a header file can be a useful form of documentation — possibly the most useful form of documentation. The header is, of necessity, accurate, up-to-date, and complete; the class documentation is not. A header consists chiefly of declarations, but it may also contain comments with helpful information; this, too, can tell you things that the class documentation might not. Also, a single header file can contain declarations for multiple classes and protocols. So it can be an excellent quick reference.

The simplest way to reach a header file is to jump to the declaration of a symbol there. For example, to reach NSString.h — the Foundation.NSString header file — Command-click on the term NSString wherever it may appear in your code. See the previous section for the various ways of jumping to a symbol declaration; since most symbols are declared in header files, these are ways of reaching header files.

When you jump to a header file from your code, if the code that you started from was a Swift file, the header file, if it is written in Objective-C, is spontaneously translated into Swift. That’s good because it tells you what you can say in Swift. But it’s bad if you were hoping to get a look at the actual Objective-C header! I sometimes add an Objective-C class to my Swift project for the sole purpose of providing a jumping-off place so that I can reach a Cocoa header without passing through the Swift translation.

In the case of the Swift language itself, the Swift header file is crucial. It’s full of numerous object types and functions that you can’t find out about any other way. For example, in Chapter 3, I mentioned the global contains function. How did I find out about this? Not from Apple’s Swift Standard Library Reference; it isn’t listed there. I found out from the Swift header file. There are also special Swift header files for Core Graphics and Foundation.

TIP

A useful trick is to write an import statement just so that you can Command-click it to reach a header. For example, if you import Swift at the top of a .swift file, the word Swift itself is a symbol that you can Command-click to jump to the Swift header.

Internet Resources

Programming has become a lot easier since the Internet came along and Google started indexing it. It’s amazing what you can find out with a Google search. Your problem is very likely one that someone else has faced, solved, and written about on the Internet. Often you’ll find sample code that you can paste into your project and adapt.

Apple’s documentation resources are available at http://developer.apple.com. These resources are updated before the changes are rolled into your doc sets for download. There are also some materials here that aren’t part of the Xcode documentation on your computer. For example, you can download iTunes videos, including the videos for all WWDC 2014 sessions (as well as for some earlier years).

Apple also maintains some public mailing lists (http://lists.apple.com/mailman/listinfo). I have long subscribed to the Xcode-users group (for questions about use of the Xcode tools) and the Cocoa-dev group (for questions about programming Cocoa). The lists are searchable, but Apple’s own search doesn’t work very well; you’re better off using Google with a site:lists.apple.com term, or http://www.cocoabuilder.com, which archives the lists.

Apple has not added a mailing list devoted to iOS programming; that’s what the Apple developer forums are supposed to be for (https://devforums.apple.com). As a registered iOS developer, you have access to these. Some interesting discussions certainly do take place here, and they are patrolled by some very helpful Apple employees; but the interface is extraordinarily clunky, and this — plus the lack of openness (to Google and to the world in general) — has limited their usefulness.

Other online resources, such as forums, have sprung up spontaneously as iOS programming has become more popular, and lots of iOS and Cocoa programmers blog about their experiences. I am particularly fond of Stack Overflow (http://www.stackoverflow.com); it isn’t devoted exclusively to iOS programming, of course, but lots of iOS programmers hang out there, questions are answered succinctly and correctly, and the interface lets you focus on the right answer quickly and easily.