Chapter    4

Getting Help

The best way to learn any new skill is to have someone show you what you need to learn. Since that’s not always possible, you’ll be happy to know that Xcode comes with plenty of built-in help features to make using Xcode less stressful and more enjoyable.

To use Xcode’s help, you first need to understand how Swift programs work and how they work with the Cocoa framework. Once you understand how a typical OS X program works and how it relies on the Cocoa framework, you’ll be better able to understand how do get the help you need and how you can understand the help you do find through Xcode.

Understanding the Cocoa Framework

When using Xcode, you have to understand that every program you create is based on the Cocoa framework that uses classes that contain various properties and methods. By using these existing classes, you can save time by not writing and testing your own code. Instead, you can just use the existing code in the Cocoa framework that already works. This frees you to spend more time focusing on writing the code that’s unique to your particular program.

To use the Cocoa framework, you must understand the principles of object-oriented programming and how objects work. To create an object, you must first define a class. A class contains the actual code that defines properties (to hold data) and methods (to manipulate data stored in its properties). Once you’ve defined a class, you can define one or more objects based on that class.

Just as a cookie cutter defines the shape of a cookie but isn’t the actual cookie, so do classes define an object but isn’t an object itself.

The Cocoa framework consists of multiple class files where many class files inherit properties and methods from other class files. When you create an OS X program, you’ll typically create objects based on Cocoa framework class files. In fact, every user interface item that you create from the Object Library is based on a Cocoa framework class.

To see what class file each user interface item is based on, let’s examine the three-user interface items you created: a label, a text field, and a button:

  1. Open the MyFirstProgram project in Xcode.
  2. Click on the MainMenu.xib file. Xcode displays your user interface.
  3. Choose View image Utilities image Show Object Library. The Object Library appears in the lower right corner of the Xcode window.
  4. Click on the Push Button item in the Object Library. A pop-up window appears as shown in Figure 4-1. Notice that this pop-up window tells you the class file (NSButton) of a push button.

    9781484212349_Fig04-01.jpg

    Figure 4-1. Finding the class file of a Push Button

  5. Click the Done button to make the pop-up window go away.
  6. Scroll through the Object Library and click on the Label item . A pop-up window appears as shown in Figure 4-2. Notice that this pop-up window tells you the class file (NSTextField) of a label.

    9781484212349_Fig04-02.jpg

    Figure 4-2. Finding the class file of a Label

  7. Scroll through the Object Library and click on the Text Field item . A pop-up window appears as shown in Figure 4-3.

    9781484212349_Fig04-03.jpg

    Figure 4-3. Finding the class file of a Text Field

By using Xcode’s simple help pop-up windows for each item in the Object Library, we’ve learned the following about our user interface:

  • Push Button is based on the NSButton class file
  • Label is based on the NSTextField class file
  • Text Field is also based on the NSTextField class file
  • The NSTextField class inherits from (is a subclass of) the NSControl class

Any time you need to find the class file of a user interface item, just click on that item in the Object Library window. To learn what properties and methods we can use for each user interface item, we need to look up all the properties and methods for that particular class. For example, if we want to know what properties and methods we can use for the text field, we have to look up the properties and methods defined by the NSTextField class.

Furthermore, since the NSTextField class inherits from the NSControl class, we can also use any properties and methods defined by the NSControl class. (If the NSControl class inherits from another class, we can use the properties and methods stored in that other class as well.)

Looking Up Properties and Methods in a Class File

Once we know what class a particular user interface item is based on, we can look up its list of properties and methods in Xcode’s documentation. There are two ways to do that:

  • Choose Help image Documentation and API reference
  • Option+click on a class name in your Swift code

Remember when we needed to find the property that stored text in both a label and a text field? Here are the steps we would follow to find this information:

  • Identify the class file that each user interface item is based on (NSTextField, which we learned by clicking on that item in the Object Library)
  • Look up Xcode’s documentation about the NSTextField class file
  • If we can’t find the information we need in the NSTextField class file, look up the NSControl class file since the NSTextField class inherits all properties and methods from the NSControl class

Looking Up Class Files with the Help Menu

Xcode’s menu bar and pull-down menus are usually the most straightforward way to find any command. So the first step is to open Xcode’s documentation window, as shown in Figure 4-4, in one of two ways:

  • Choose Help image Documentation and API Reference
  • Press Shift+Command+0 (the number zero)

9781484212349_Fig04-04.jpg

Figure 4-4. The Xcode Documentation window

 Note  To make the Documentation window less cluttered, click on the Show/Hide Navigator icon.

  1. Click in the Search documentation text field at the top of the Documentation window, type NSTextField, and press Return. The Documentation window displays information about the NSTextField class.
  2. Scroll through the Table of Contents pane to view information about the NSTextField class. If you click on a topic in the Table of Contents pane, the Documentation window displays additional information as shown in Figure 4-5. However, there’s nothing in the NSTextField documentation that explains how it stores text. To find that answer, we need to next look in the class that NSTextField inherits from, which is NSControl.

    9781484212349_Fig04-05.jpg

    Figure 4-5. Selecting an item in the Table of Contents pane displays information in the right pane

  3. Click NSControl that appears to the right of the Inherits from: label. Notice that NSTextField inherits from NSControl, which inherits from NSView, which inherits from NSResponder, which inherits from NSObject. To find every property and method available to a label or text field (both based on the NSTextField class), we could exhaustively search each of these class files as well.
  4. Click on the Getting and Setting the Control’s Value in the Table of Contents pane of NSControl as shown in Figure 4-6. Notice that the property that stores text data in the NSControl class is called stringValue.

    9781484212349_Fig04-06.jpg

    Figure 4-6. The Documentation window lists all the properties in NSControl that stores data

Once we know that we can use the stringValue property to hold text data in the NSControl class, we also know that we can use the stringValue property to hold text data in the NSTextField class. Since both our label and text field are based on the NSTextField class (which we discovered by clicking on them in the Object Library), we know we can access the text data of both the label and text field using the stringValue property.

Looking Up Class Files with Quick Help

Using the Documentation window to look up class files can be handy, but Xcode offers another method called Quick Help. To use Quick Help, you need to move the cursor or mouse pointer over a class file name in a file containing Swift code, then choose one of the following methods:

  • Choose Help image Quick Help for Selected Item
  • Press Control+Command+Shift+?
  • Hold down the Option key and click on a class file name

Quick Help then displays a pop-up window containing a brief description of the selected class file, giving you the option to view the full description in the Documentation window if you choose. To see how Quick Help works using the Option key and the mouse, follow these steps:

  1. Make sure the MyFirstProgram is loaded into Xcode.
  2. Click the AppDelegate.swift file in the Project Navigator. Xcode displays the contents of the AppDelegate.swift file in the middle pane.
  3. Hold down the Option key and move the mouse over the NSTextField word in the IBOutlet. The mouse pointer turns into a question mark as shown in Figure 4-7.

    9781484212349_Fig04-07.jpg

    Figure 4-7. Holding down the Option key turns the mouse pointer into a question mark when hovering over a class file name

  4. While holding down the Option key with the mouse pointer over NSTextField, click the mouse. Xcode displays a pop-up window briefly describing the features of the NSTextField class as shown in Figure 4-8.

    9781484212349_Fig04-08.jpg

    Figure 4-8. Option+clicking on a class file name displays a pop-up window describing that class file

  5. Click on NSTextField Class Reference at the bottom of the pop-up window next to the Reference label. Xcode displays the Documentation window listing the NSTextField class file (see Figure 4-5).

Option+clicking is just a way to open the Documentation window without going through the Help image Documentation and Reference API command and typing a class file name.

Browsing the Documentation

Quick Help can display information about specific class files, but what if you know you need information but don’t know where to find it? That’s when you can spend time browsing through the Documentation window and skimming through the different help topics until you find what you want.

Even if you don’t find what you want, chances are good you’ll stumble across some interesting information about Xcode or OS X that could come in handy sometime in the future. When browsing through Xcode’s documentation, you can look up information specific to iOS, OS X, or Xcode.

If you find something interesting, you can bookmark it. That way you’ll be able to find it quickly again later. You can also send information by e-mail or text messaging to share useful information with others.

To browse through the Documentation, follow these steps:

  1. Choose Help image Documentation and API Reference. The Documentation window appears.
  2. Click the Show/Hide Navigator icon to make sure the Navigator pane appears and lists categories of topics such as iOS, OS X, and Xcode as shown in Figure 4-9.

    9781484212349_Fig04-09.jpg

    Figure 4-9. The Navigator pane of the Documentation window displays categories of different information

  3. Click the gray disclosure triangle that appears to the left of a category such as the OS X or Xcode category. A list of additional topics (with their own gray disclosure triangles) appears. By continuing to click the disclosure triangle of topics, you will eventually find lists of topics that you can click on to view that information as shown in Figure 4-10.

    9781484212349_Fig04-10.jpg

    Figure 4-10. Each category lists several other categories of various topics

  4. Click in the Share icon that appears in the upper right corner of the Documentation window as shown in Figure 4-11. If you click Email Link, the Mail program will load a blank e-mail message with a link to that page in the documentation. If you click Add Bookmark, Xcode stores that documentation page as a bookmark.

    9781484212349_Fig04-11.jpg

    Figure 4-11. The Share icon lets you bookmark a page or share it with others

After you’ve bookmarked one or more pages, you can view your bookmarks by clicking the Show documentation bookmarks icon as shown in Figure 4-12. Now you can click on a bookmark and see that documentation page right away without having to hunt around for it.

9781484212349_Fig04-12.jpg

Figure 4-12. Viewing bookmarked pages

To delete a bookmark, just right-click over it so a pop-up menu appears. Then choose Delete.

When you want to view the documentation library categories again (iOS, OS X, and Xcode), just click the Browse the documentation library icon as shown in Figure 4-13.

9781484212349_Fig04-13.jpg

Figure 4-13. The Browse the documentation library icon

Searching the Documentation

Quick Help can display information about specific class files and browsing the documentation can help you explore all the vast information about iOS, OS X, and Xcode. The problem is that Quick Help is only useful for finding information about class files and browsing the documentation can be time-consuming. If you know what you want to find, you can just search for it instead.

When searching for information, type as much as possible to narrow your search results. If you just type a single letter or word, Xcode’s documentation will bombard you with irrelevant results.

To see how searching the documentation window works, try the following:

  1. Choose Help image Documentation and API Reference. The Documentation window appears.
  2. Click in the Search documentation text field and type text. A menu of different text results appears that you can click on to get more information as shown in Figure 4-14.

    9781484212349_Fig04-14.jpg

    Figure 4-14. A menu of results for “text”

  3. Tap the spacebar to create a space after text. Notice now the menu displays entirely different text results as shown in Figure 4-15.

    9781484212349_Fig04-15.jpg

    Figure 4-15. Just adding an extra space after a search term can display a different menu of results

By searching through the documentation, you can find what you need quickly and easily.

Using Code Completion

Back in Chapter 3 when you started typing Swift code, you may have noticed something odd. Each time you typed part of a Swift command, the Xcode editor may have displayed grayed text and a menu of possible commands that match what you partially typed as shown in Figure 4-16.

9781484212349_Fig04-16.jpg

Figure 4-16. Code completion suggests a likely command you may be trying to type

This feature is called Code Completion and is Xcode’s way of helping you type long commands without actually typing every character yourself. When you see grayed out text and a menu, you have three choices:

  • Press the Tab key to let Xcode automatically type part of the grayed out text. (You may need to press the Tab key several times to completely select all the grayed out text.)
  • Double-click on a command in the pop-up menu to type that command automatically.
  • Keep typing.

If you keep typing, Xcode keeps displaying new grayed out text that it thinks you may be trying to type along with a menu of different commands that match what you’ve typed so far. Let’s see how code completion works:

To see how searching the documentation window works, try the following:

  1. Make sure your MyFirstProgram is loaded in Xcode.
  2. Click on AppDelegate.swift in the Project Navigator pane. The contents of the AppDelegate.swift file appears in the middle Xcode pane.
  3. Modify the @IBAction changeCase (sender: NSButton) code by deleting the one line between the curly brackets so it now appears as follows:
    @IBAction func changeCase(sender: NSButton) {

    }
  4. Move the cursor between the curly brackets of this @IBAction method and type labelText.s and notice that grayed out text appears, and a menu of possible commands also appears as shown in Figure 4-17.

    9781484212349_Fig04-17.jpg

    Figure 4-17. Code completion suggests stringValue as a possible command

  5. Tab the Tab key. The first time you tap the Tab key, Xcode types “string.”
  6. Tap the Tab key a second time and now Xcode types the complete “stringValue.”
  7. Type = messageText.stringValue.uppercaseString. Notice that as you type, Code Completion keeps showing different grayed out text and commands in the pop-up menu.

By using Code Completion, you can type commands faster and more accurately. If you start typing a command and you don’t see Code Completion’s grayed out text or menu appear, that could be a signal that you mistyped the command. Code Completion is just one more way Xcode tries to make typing code easier for you.

Understanding How OS X Programs Work

To help you better understand what all of Xcode’s help documentation means, you need to understand how OS X programs work. In the old days when programs were small, programmers stored all program commands in a single file. Then the computer started at the first command at the top of the file, worked its way down line by line, and stopped when it reached the end of the file.

Today programs are much larger so they’re often divided into multiple files. No matter how many files you divide your program into, Xcode treats everything as if it were stored in a single file. Dividing a program into files is for your convenience.

Let’s examine your MyFirstProgram line by line so you can understand what’s happening. When you view Swift code in Xcode, you’ll notice that the Xcode editor color codes different text. These colors help you identify the purpose of different text as follows:

  • Green – Comments that Xcode completely ignores. Comments are meant to explain something about the nearby code.
  • Purple – Keywords of the Swift language.
  • Red – Text strings.
  • Blue – Class file names.
  • Black – Commands.

The very first line tells Xcode to import or include all the code in the Cocoa framework as part of your program. The line looks like this:

import Cocoa

The next line runs a Swift function that loads your user interface (MainMenu.xib) and creates an object from your AppDelegate class. This basically gets your whole program running as a generic Macintosh program. The line looks like this:

@NSApplicationMain

The next line defines a class called AppDelegate that is based on the NSObject class and uses the NSApplicationDelegate protocol (which you’ll learn about shortly). This line looks like this:

class AppDelegate: NSObject, NSApplicationDelegate {

The next three lines define IBOutlets that connect this Swift code to the user interface items: the window of the user interface along with the label and text field. The window is based on the NSWindow class (defined in the Cocoa framework) while the label and text fields are based on the NSTextField class. These lines look like this:

@IBOutlet weak var window: NSWindow!
@IBOutlet weak var labelText: NSTextField!
@IBOutlet weak var messageText: NSTextField!

The next three lines define an IBAction method that’s connected to the push button on the user interface. The code takes the text stored in messageText (the text field) and converts it to uppercase. Then it stores the uppercase text into labelText (the label). Both the label and text field are based on the NSTextField class (defined in the Cocoa framework). The lines look like this:

@IBAction func changeCase(sender: NSButton) {
    labelText.stringValue = messageText.stringValue.uppercaseString
}

The remaining code defines two functions that are empty so they don’t do anything. If you typed code inside of these functions, the code would run right after your program started up (applicationDidFinishLaunching) or it would run as soon as your program ended (applicationWillTerminate).

When MyFirstProgram runs, it imports the Cocoa framework and runs to display a generic Macintosh program on the screen that includes your user interface. The applicationDidFinishLaunching function runs, but since it doesn’t contain any code, nothing happens. Now the program stops and waits for something to happen.

If the user quits out of the program, the applicationWillTerminate function would run, but since it doesn’t contain any code, nothing happens.

When the user clicks the Change Case button, it runs the IBAction changeCase method. The only Swift command in this IBAction method takes the text from the text field (stored in the stringValue property of messageText), capitalizes it, and stores the capitalized text in the label (displayed by the stringValue property of labelText).

Now that you’ve seen how the MyFirstProgram works, let’s look at OS X programming from a more theoretical standpoint. First, creating a program involves using class files defined by the Cocoa framework. When you place items on a user interface, you’re using Cocoa framework class files (such as NSTextField and NSButton).

When you define a class in your AppDelegate.swift file, you’re also using a class from the Cocoa framework file (NSObject).

A typical OS X program creates objects from the class files in the Cocoa framework and any class files you may define in your Swift files. Objects now communicate with one another in one of two ways:

  • Storing or retrieving data from properties stored in other objects
  • Calling methods stored in other objects

To store data in an object’s property, you have to specify the object name and its property on the left side of an equal sign and a value on the right like this:

labelText.stringValue = "Hello, world!"

To retrieve data from an object’s property, you have to specify a variable to hold data on the left side of an equal sign and the object name and its property on the right like this:

let warning = labelText.stringValue

To call a method stored in another object, you have to specify the object’s name and the method to use like this:

messageText.stringValue.uppercaseString

This command tells Xcode to run the uppercaseString method on the stringValue property stored in the messageText object.

Setting property values, retrieving property values, and calling methods to run are the three ways objects communicate with each other.

When you create a class, you must define the class file to use such as:

class AppDelegate: NSObject

This line tells Xcode to define a class called AppDelegate and base it on the class file called NSObject (which is defined in the Cocoa framework).

When you create a class based on an existing class, that class automatically includes all the properties and methods defined by that class. So in the above line of code that defines the AppDelegate class, any object created from the AppDelegate class automatically has all the properties and methods defined by the NSObject class.

Sometimes a class file doesn’t have all the methods you may need. To fix this, you can inherit from an existing class and then define a new method in your class. However, if you create a method name that you want other classes to use, a second alternative is to define something called a protocol.

A protocol is nothing more than a list of related method names together but doesn’t include any Swift code to make those methods actually do anything. In the code below, the AppDelegate class is not only based on the NSObject class file, but also uses methods defined by the NSApplicationDelegate protocol.

If you open the Documentation window and search for NSApplicationDelegate protocol, you’ll see a list of method names defined by the NSApplicationDelegate protocol, such as applicationDidFinishLaunching or applicationWillTerminate as shown in Figure 4-18.

9781484212349_Fig04-18.jpg

Figure 4-18. The NSApplicationDelegate protocol in the Documentation window

The AppDelegate class inherits properties and methods from the NSObject class and uses the method names defined by the NSApplicationDelegate protocol. Any class based on a protocol must write Swift code to make those protocol methods actually do something. In technical terms, this is known as “implementing or conforming to a protocol.”

So the Cocoa framework actually consists of classes and protocols. Classes define objects, and protocols define commonly used method names that different classes may need.

When you write OS X programs, you’ll often use both Cocoa framework classes and protocols. When you use a Cocoa framework class, you can use methods that already know how to work such as the uppercaseString method that knows how to capitalize text.

When you use a Cocoa framework protocol, you’ll need to write Swift code to make that method actually work. When browsing through Xcode’s documentation, keep your eye out for this difference between classes and protocols.

Let’s see an example of both classes and protocols in the Xcode documentation window:

  1. Make sure your MyFirstProgram is loaded in Xcode.
  2. Click on the AppDelegate.swift file in the Project Navigator. Xcode’s middle pane displays the contents of that .swift file.
  3. Move the cursor in NSApplicationDelegate.
  4. Choose Help image Quick Help for Selected Item, or hold down the Option key and click on NSApplicationDelegate. A quick help pop-up window appears as shown in Figure 4-19, explaining how NSApplicationDelegate is a protocol.

    9781484212349_Fig04-19.jpg

    Figure 4-19. The NSApplicationDelegate Quick Help pop-up window

  5. Click NSApplicationDelegate Protocol Reference. The NSApplicationDelegate protocol reference appears in the Documentation window (see Figure 4-18).
  6. Type NSTextField in the Search documentation field of the Documentation window and press Return. Notice that the Documentation window explains which classes NSTextField inherits from (the Inherits from: label) and which protocols might be useful when dealing with user interface items (the Conforms to: label) as shown in Figure 4-20.

    9781484212349_Fig04-20.jpg

    Figure 4-20. Seeing related classes and protocols

Protocols add methods to a class without the need to create a new class, but you never need to use protocols. When you write programs in Xcode, you’ll use Cocoa framework classes and protocols. Then for the unique purposes of your program, you’ll likely create your own classes and protocols as well.

When browsing through Xcode’s documentation, look for properties and methods in classes before writing your own code. If you don’t find the properties and methods you need in one class, look in other classes listed next to the Inherits from: label.

If you need some useful methods, look in the different protocols listed next to the Conforms to: label. Only after you’ve determined that a property or method doesn’t exist in a related class or protocol should you write your own Swift code to do something.

For example, in the MyFirstProgram project, we could have written Swift code to capitalize text typed into the text field. However, it was much easier to just use the existing uppercaseString method instead. That saved us time writing code and debugging it when we could just use proven code in the Cocoa framework instead.

The more you know about the Cocoa framework, the less work you’ll have to do writing your own programs. Use Xcode’s documentation to help you better understand all the classes and protocols that make up the entire Cocoa framework.

Since the Cocoa framework is so large, don’t bother trying to learn everything at once. Just learn what you need and ignore the rest. Gradually the more you use Xcode and write programs, the more likely you’ll need and learn the other parts of the Cocoa framework.

The general idea is to rely on the Cocoa framework as much as possible and only write Swift code when you have to. This makes it easy to write reliable software quickly with less effort.

Summary

Learning Xcode can be daunting, so learn it slowly by relying on Xcode’s documentation. If you need help in a hurry, use Quick Help to find information about the Cocoa framework classes. If need help on a particular topic, search the documentation.

For those times when you’re just curious, browse through Xcode’s documentation for iOS, OS X, and Xcode so you can see the vast amount of features available. Through random browsing, you can often learn interesting information about Xcode or writing programs for iOS and OS X.

As you can see, learning to write programs involves learning about Xcode, learning about the Cocoa framework, and learning the Swift programming language. Just take it easy, learn only what you need to know, and gradually keep expanding your knowledge. Through steady progress, you’ll learn more and more until one day you’ll realize how much you actually know.

Learning to write iOS and OS X programs with Xcode won’t happen overnight, but you’ll be surprised how much you can learn through steady progress over time. Just practice writing programs and rely on Xcode’s documentation available from the Help menu. Before you know it, you’ll be capable of writing small programs with confidence, and eventually larger and more complicated ones.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset