Sunday, December 15, 2013

Build Phases in Xcode


Edit the Empty Window target and click Build Phases at the top of the editor (Figure 6-8). These are the stages by which your app is built. By default, there are three of them with content — Compile Sources, Link Binary With Libraries, and Copy Bundle Resources — and those are the only stages you’ll usually need, though you can add others. The build phases are both a report to you on how the target will be built and a set of instructions to Xcode on how to build the target; if you change the build phases, you change the build process. Click each build phase to see a list of the files in your target to which that build phase will apply.
The meanings of the three build phases are pretty straightforward:
Compile Sources
Certain files (your code) are compiled, and the resulting compiled code is copied into the app.
This build phase typically applies to all of the target’s .m files; those are the code files that constitute the target. Sure enough, it currently contains View‐ Controller.m, AppDelegate.m, and main.m. If you add a new class to your project, you’ll specify that it should be part of the app target, and the .m file will automatically be added to the Compile Sources build phase.
Link Binary With Libraries
Certain libraries, usually frameworks, are linked to the compiled code (now referred to, following compilation, as the binary), so that it will expect them to be present on the device when the app runs.
This build phase currently lists three frameworks. I’ll talk later in this chapter about the mechanics of linking the binary with additional frameworks.
How to build phases in Xcode

Copy Bundle Resources
Certain files are copied into the app, so that your code or the system can find them there when the app runs. For example, if your app had an icon image, it would need to be copied into the app so the device could find and display it.
This build phase currently applies to the asset catalog; any images you add to the asset catalog will be copied into your app as part of the catalog. It also currently lists InfoPlist.strings and your app’s .storyboard file.
Copying doesn’t necessarily mean making an identical copy. Certain types of file are automatically treated in special ways as they are copied into the app bundle. For example, copying the asset catalog means that icons and launch images in the cat‐ alog are written out to the top level of the app bundle; copying the .storyboard file means that it is transformed into a .storyboardc file, which is itself a bundle con‐ taining nib files.
You can alter these lists manually, and sometimes you may need to do so. For instance, if something in your project, such as a sound file, was not in Copy Bundle Resources and you wanted it copied into the app during the build process, you would drag it from the Project navigator into the Copy Bundle Resources list, or (easier) click the Plus button beneath the Copy Bundle Resources list to get a helpful dialog listing everything in your project. Conversely, if something in your project was in Copy Bundle Resources and you didn’t want it copied into the app, you would delete it from the list; this would not delete it from your project, from the Project navigator, or from the Finder, but only from the list of things to be copied into your app.
A useful trick is to add a Run Script build phase, which runs a custom shell script late in the build process. To do so, choose Editor → Add Build Phase → Add Run Script Build Phase. Open the newly added Run Script build phase to edit the custom shell script. A minimal shell script might read:
    echo "Running the Run Script build phase"
The “Show environment variables in build log” checkbox causes the build process’s environment variables and their values to be listed in the build log during the Run Script build phase. This alone can be a good reason for adding a Run Script build phase; you can learn a lot about how the build process works by examining the environment vari‐ ables.
How to build phases in Xcode

Monday, December 9, 2013

The Target in Xcode


A target is a collection of parts along with rules and settings for how to build a product from them. Whenever you build, what you’re really building is a target.

Select the Empty Window project at the top of the Project navigator, and you’ll see two things on the left side of the editor: the project itself, and a list of your targets. (This list can appear either as a column on the left side of the editor, as in Figure 6-8, or as a pop- up menu at the top left of the editor if that column is collapsed to save space.) Our Empty Window project comes with two targets: the app target, called Empty Window (just like the project itself), and the tests target, called Empty WindowTests. 

Under certain cir‐ cumstances, you might add further targets to a project. For example, you might want to write an app that can be built as an iPhone app or as an iPad app — two different apps that share a lot of the same code. So you might want one project that builds both apps through separate targets.
If you select the project in the left column or pop-up menu of the editor, you edit the project. If you select a target in the left column or pop-up menu of the editor, you edit the target. I’ll use those expressions a lot in later instructions.

Let’s concentrate on the app target, Empty Window. This is the target that you use to build and run your app. Its settings are the settings that tell Xcode how your app is to be built; its product is the app itself. (The tests target, Empty WindowTests, creates a special executable whose purpose is to test your app’s code. 

The Project File and Its Dependents in Xcode


The first item in the Project navigator (Command-1) represents the project itself. (In the Empty Window project that we created earlier in this chapter, it is called Empty Window.) Hierarchically dependent upon it are items that contribute to the building of the project. Many of these items, including the project itself, correspond to items on disk in the project folder.

To survey this correspondence, let’s examine the project folder in the Finder simulta‐ neously with the Xcode project window. Select the project listing in the Project navigator and choose File → Show in Finder (Figure 6-7).

The Finder displays the contents of your project folder. The most important of these is Empty Window.xcodeproj. This is the project file, corresponding to the project listed in the Project navigator. All Xcode’s knowledge about your project — what files it consists of and how to build the project — is stored in this file. To open a project from the Finder, double-click the project file. Alternatively, you can drag the project folder onto Xcode’s icon (in the Finder, in the Dock, or in the application switcher) and Xcode will locate the project file and open it for you; thus, you might never need to open the project folder at all!
The project File and its Dependents in Xcode
 Let’s consider how the groups and files displayed hierarchically down from the project in the Project navigator correspond to reality on disk as portrayed in the Finder (Figure 6-7). (Recall that group is the technical term for the folder-like objects shown in the Project navigator.) Groups in the Project navigator don’t necessarily correspond to folders on disk in the Finder, and folders on disk in the Finder don’t necessarily correspond to groups in the Project navigator:
  • The Empty Window group corresponds directly to the Empty Window folder on disk. Files within the Empty Window group, such as AppDelegate.m, correspond to real files on disk that are inside the Empty Window folder. If you were to create additional code files (which, in real life, you would almost certainly do in the course of developing your project), you would likely put them in the Empty Window group in the Project navigator, and they, too, would then be in the Empty Window folder on disk. (That, however, is not a requirement; your files can live anywhere and your project will still work fine.)
    Similarly, the Empty Window Tests group corresponds to the Empty Window Tests folder on disk, and the file Empty_WindowTests.m listed inside the Empty Window Tests group lives inside the Empty Window Tests folder.
    These two group–folder pairs correspond to the two targets of your project. I’ll talk in the next section about what a target is. There is no law requiring that a target have a corresponding group in the Project navigator and a corresponding folder in the project folder, but the project template sets things up that way as an organiza‐ tional convenience: it clarifies the project’s structure in the Project navigator, and it prevents a lot of files from appearing at the top level of the project folder.

  • The Supporting Files group inside the Empty Window group, on the other hand, corresponds to nothing on disk; it’s just a way of clumping some items together in the Project navigator, so that they can be located easily and can be shown or hidden together. The things inside this group are real, however; you can see that the four files Empty Window-Info.plist, InfoPlist.strings, main.m, and Empty Window- Prefix.pch do exist on disk — they’re just not inside anything called Supporting Files. (The Supporting Files group inside the Empty WindowTests group is similar.)

  • Two files in the Empty Window group, InfoPlist.strings and Main.storyboard, ap‐ pear in the Finder inside folders that don’t visibly correspond to anything in the Project navigator: Main.storyboard, on disk, is inside a folder called Base.lproj, and InfoPlist.strings, on disk, is inside a folder called en.lproj

  • The item Images.xcassets in the Project navigator corresponds to a specially struc‐ tured folder Images.xcassets on disk. This is an asset catalog (new in Xcode 5); you add images to the asset catalog in Xcode, which maintains that folder on disk for you. This makes it easy for you to have multiple related images, such as app icons of different sizes, without having to see them all listed directly in the Project navi‐ gator. 
    You may be tempted to find all this confusing. Don’t! Remember what I said about not involving yourself with the project folder on disk in the Finder. Keep your attention on the Project navigator, make your modifications to the project there, and all will be well.
    Feel free, as you develop your project and add files to it, to add further groups. The purpose of groups is to make the Project navigator work well for you. They don’t affect how the app is built, and by default they don’t correspond to any folder on disk; they are just an organizational convenience within the Project navigator. To make a new group, choose File → New → Group. To rename a group, select it in the Project navigator and press Return to make the name editable. For example, if some of your code files have to do with a login screen that your app sometimes presents, you might clump them together in a Login group. If your app is to contain some sound files, you might put them into a Sounds group. And so on.
    The things in the Frameworks group and the Products group don’t correspond to any‐ thing in the project folder, but they do correspond to real things that the project needs to know about in order to build and run:

    Frameworks
    This group, by convention, lists frameworks (Cocoa code) on which your code depends. Frameworks exist on disk, but they are not built into your app when it is constructed; they don’t have to be, because they are present also on the target device (an iPhone, iPod touch, or iPad). Instead, the frameworks are linked to the app, meaning that the app knows about them and expects to find them on the device when it runs. Thus, all the framework code is omitted from the app itself, saving considerable space.
    (Starting in Xcode 5, the new modules feature permits frameworks to be linked to your code without being listed here. I’ll talk about modules at the end of this chap‐ ter.)

    Products
    This group, by convention, automatically holds a reference to the executable bundle generated by building a target. 
 

Sunday, December 8, 2013

The Editor in Xcode


In the middle of the project window is the editor. This is where you get actual work done, reading and writing your code, or designing your interface in a .storyboard or .xib file. The editor is the core of the project window. You can hide the Navigator pane, the Utilities pane, and the Debug pane, but there is no such thing as a project window without an editor (though you can cover the editor completely with the Debug pane).

The editor provides its own form of navigation, the jump bar across the top. Not only does the jump bar show you hierarchically what file is currently being edited, but also it allows you to switch to a different file. In particular, each path component in the jump bar is also a pop-up menu. These pop-up menus can be summoned by clicking on a path component, or by using keyboard shortcuts (shown in the second section of the View → Standard Editor submenu). For example, Control-4 summons a hierarchical pop-up menu, which can be navigated entirely with the keyboard, allowing you to choose a different file in your project to edit. Moreover, each pop-up menu in the jump bar also has a filter field; to see it, summon a pop-up menu from the jump bar and start typing. Thus you can navigate your project even if the Project navigator isn’t showing.

The symbol at the left end of the jump bar (Control-1) summons a hierarchical menu (the Related Files menu) allowing navigation to files related to the current one. What appears here depends not only on what file is currently being edited but on the current selection within that file. This is an extremely powerful and convenient menu, and you should take time to explore it. If this file is one of a pair of class files (.m or .h), you can switch to the other member of the pair (Counterparts). You can navigate to related class files and header files (Superclasses, Subclasses, and Siblings; siblings are classes with the same superclass). You can navigate to files included by this one, and to files that include this one; you can view methods called by the currently selected method, and that call the currently selected method.
The editor remembers the history of things it has displayed, and you can return to previously viewed content with the Back button in the jump bar, which is also a pop- up menu from which you can choose. Alternatively, choose Navigate → Go Back (Command-Control-Left).

It is extremely likely, as you develop a project, that you’ll want to edit more than one file simultaneously, or obtain multiple views of a single file so that you can edit two areas of it simultaneously. This can be achieved in three ways: assistants, tabs, and secondary windows.

Assistants
You can split the editor into multiple editors by summoning an assistant pane. To do so, click the second Editor button in the toolbar, or choose View → Assistant Editor → Show Assistant Editor (Command-Option-Return). Also, by default, adding the Option key to navigation opens an assistant pane; for example, Option- click in the Navigator pane, or Option-choose in the jump bar, to navigate by open‐ ing an assistant pane (or to navigate in an existing assistant pane if there is one). To remove the assistant pane, click the first Editor button in the toolbar, or choose View → Standard Editor → Show Standard Editor (Command-Return), or click the X button at the assistant pane’s top right.

Tabs
You can embody the entire project window interface as a tab. To do so, choose File → New → Tab (Command-T), revealing the tab bar (just below the toolbar) if it wasn’t showing already. Use of a tabbed interface will likely be familiar from appli‐ cations such as Safari. You can switch between tabs by clicking on a tab, or with Command-Shift-}. At first, your new tab will look largely identical to the original window from which it was spawned. But now you can make changes in a tab — change what panes are showing or what file is being edited, for example — without affecting any other tabs. Thus you can get multiple views of your project. You can assign a descriptive name to a tab: double-click on a tab name to make it editable.

Secondary windows
A secondary project window is similar to a tab, but it appears as a separate window instead of a tab in the same window. To create one, choose File → New → Window (Command-Shift-T). Alternatively, you can promote a tab to be a window by drag‐ ging it right out of its current window.
You can determine how assistant panes are to be arranged. To do so, choose from the View → Assistant Editor submenu. I usually prefer All Editors Stacked Vertically, but it’s purely a matter of taste. Once you’ve summoned an assistant pane, you can split it further into additional assistant panes. To do so, click the Plus button at the top right of an assistant pane. To move the contents of the current assistant pane into the main editor, choose Navigate → Open in Primary Editor. To dismiss an assistant pane, click the X button at its top right.
What makes an assistant pane an assistant, and not just a form of split-pane editing, is that it can bear a special relationship to the primary editor pane. The primary editor pane is the one whose contents, by default, are determined by what you click on in the Navigator pane; an assistant pane, meanwhile, can respond to what file is being edited in the primary editor pane by changing intelligently what file it (the assistant pane) is editing. This is called tracking
The Editor in Xcode

To see tracking in action, open a single assistant pane and use the first component in its jump bar (Control-4). This is the Tracking menu. It’s like the Related Files menu that I discussed a moment ago, but you can select a category to determine automatic tracking behavior. For example, choose Counterparts (Figure 6-6). Now use the Project navigator to select AppDelegate.m; the primary editor pane displays this file, and the assistant automatically displays AppDelegate.h. Next, use the Project navigator to select App‐ Delegate.h; the primary editor pane displays this file, and the assistant automatically displays AppDelegate.m. If a category has multiple files, the assistant navigates to the first one, and a pair of arrow buttons appears at the right end of the assistant’s jump bar, with which you can navigate among the others (or use the second jump bar component, Control-5). There’s a lot of convenience and power lurking here, which you’ll explore as you need it. You can turn off tracking by setting the assistant’s first jump bar com‐ ponent to Manual.

There isn’t a strong difference between a tab and a secondary window; which you use, and for what, will be a matter of taste and convenience. I find that the advantage of a secondary window is that you can see it at the same time as the main window, and that it can be small. Thus, when I have a file I frequently want to refer to, I often spawn off a secondary window displaying that file, sized fairly small and without any panes other than the editor.

Tabs and windows come in handy in connection with custom behaviors. For example, as I mentioned before, it’s important to be able to view the console while debugging; I like to see it at the full size of the project window, but I also want to be able to switch back to viewing my code. So I’ve created a custom behavior (click the Plus button at the bottom of the Behaviors pane of the Preferences window) that performs two actions: Show tab named Console in active window, and Show debugger with Console View.

Moreover, I’ve given that behavior a keyboard shortcut. Thus at any time I can press my keyboard shortcut, and we switch to the Console tab (creating it if it doesn’t exist) displaying nothing but the console. This is just a tab, so I can switch between it and my code with Command-Shift-}. 

The Utilities Pane in Xcode


The Utilities pane is the column at the right of the project window. It contains inspectors that provide information about the current selection or its settings; if those settings can be changed, this is where you change them. It also contains libraries that function as a source of objects you may need while editing your project. The Utilities pane’s impor‐ tance emerges mostly when you’re editing a .storyboard or .xib file. But it can be useful also while editing code, because Quick Help, a form of documentation , is displayed here as well, plus the Utilities pane is the source of code snippets. To toggle the visibility of the Utilities pane, choose View → Utilities → Hide/Show Utilities (Command-Option-0). You can change the Utilities pane’s width by dragging the vertical line at its left edge.
The Utilities pane consists of numerous palettes, which are clumped into multiple sets, which are themselves divided into two major groups: the top half of the pane and the bottom half of the pane. You can change the relative heights of these two halves by dragging the horizontal line that separates them.
The top half
What appears in the top half of the Utilities pane depends on what’s selected in the current editor. There are three main cases:
A code file is being edited
The top half of the Utilities pane shows either the File inspector or Quick Help. Toggle between them with the icons at the top of this half of the Utilities pane, or with their keyboard shortcuts (Command-Option-1, Command-Option-2). The File inspector is rarely needed, but Quick Help can be useful as documen‐ tation. The File inspector consists of multiple sections, each of which can be expanded or collapsed by clicking its header.
A .storyboard or .xib file is being edited
The top half of the Utilities pane shows, in addition to the File inspector and Quick Help, the Identity inspector (Command-Option-3), the Attributes in‐ spector (Command-Option-4), the Size inspector (Command-Option-5), and the Connections inspector (Command-Option-6). These can consist of mul‐ tiple sections, each of which can be expanded or collapsed by clicking its header.
An asset catalog is being edited
In addition to the File inspector and Quick Help, the Attributes inspector (Command-Option-4) lets you determine which variants of an image are listed.
The bottom half
The bottom half of the Utilities pane shows one of four libraries. Toggle between them with the icons at the top of this half of the Utilities pane, or with their keyboard shortcuts. They are the File Template library (Command-Option-Control-1), the Code Snippet library (Command-Option-Control-2), the Object library (Command-Option-Control-3), and the Media library (Command-Option- Control-4). The Object library is the most important; you’ll use it heavily when editing a .storyboard or .xib file.
To see a help pop-up describing the currently selected item in a library, press Spacebar. 

Saturday, December 7, 2013

The Navigator Pane in Xcode


The Navigator pane is the column of information at the left of the project window. Among other things, it’s your primary mechanism for controlling what you see in the main area of the project window (the editor). An important use pattern for Xcode is: you select something in the Navigator pane, and that thing is displayed in the editor.
It is possible to toggle the visibility of the Navigator pane (View → Navigators → Hide/ Show Navigator, or Command-0); for example, once you’ve used the Navigator pane to reach the item you want to see or work on in the editor, you might hide the Navigator pane temporarily to maximize your screen real estate (especially on a smaller monitor). You can change the Navigator pane’s width by dragging the vertical line at its right edge.
The Navigator pane itself can display eight different sets of information; thus, there are actually eight navigators. These are represented by the eight icons across its top; to switch among them, use these icons or their keyboard shortcuts (Command-1, Command-2, and so on). You will quickly become adept at switching to the navigator you want; their keyboard shortcuts will become second nature. If the Navigator pane is hidden, pressing a navigator’s keyboard shortcut both shows the Navigator pane and switches to that navigator.
Depending on your settings in the Behaviors pane of Xcode’s preferences, a navigator might show itself automatically when you perform a certain action. For example, by default, when you build your project, if warning messages or error messages are generated, the Issue navigator will appear. This automatic behavior will not prove trouble‐ some, because it is generally precisely the behavior you want, and if it isn’t, you can change it; plus you can easily switch to a different navigator at any time.
Let’s begin experimenting immediately with the various navigators:
Project navigator (Command-1)
Click here for basic navigation through the files that constitute your project. For example, in the Empty Window folder (these folder-like things in the Project nav‐ igator are actually called groups), click AppDelegate.m to view its code in the editor (Figure 6-2).
At the top level of the Project navigator, with a blue Xcode icon, is the Empty Win‐ dow project itself; click it to view the settings associated with your project and its targets. Don’t change anything here without knowing what you’re doing! I’ll talk later in this chapter about what these settings are for.
The filter bar at the bottom of the Project navigator lets you limit what files are shown; when there are many files, this is great for quickly reaching a file with a known name. For example, try typing “delegate” in the filter bar search field. Don’t forget to remove your filter when you’re done experimenting. 


Symbol navigator (Command-2)
A symbol is a name, typically the name of a class or method. Depending on which of the three icons in the filter bar at the bottom you highlight, you can view Cocoa’s built-in symbols or the symbols defined in your project. The former can be a useful form of documentation; the latter can be helpful for navigating your code. For example, highlight the first two icons in the filter bar (the first two are blue, the third is dark), and see how quickly you can reach the definition of AppDelegate’s applicationDidBecomeActive: method.
Try highlighting the filter bar icons in various ways to see how the contents of the Symbol navigator change. Type in the search field in the filter bar to limit what appears in the Symbol navigator; for example, try typing “active” in the search field, and see what happens.
Search navigator (Command-3)
Xcode navigator plane

This is a powerful search facility for finding text globally in your project, and even in the headers of Cocoa frameworks. You can also summon the Search navigator with Find → Find in Project (Command-Shift-F). The words above the search field show what options are currently in force; they are pop-up menus, so click one to change the options. Try searching for “delegate” (Figure 6-3). Click a search result to jump to it in your code.
You can type in the other search field, the one in the filter bar at the bottom, to limit further which search results are displayed. (I’m going to stop calling your attention to the filter bar now, but every navigator has it in some form.) 


Issue navigator (Command-4)
You’ll need this navigator primarily when your code has issues. This doesn’t refer to emotional instability; it’s Xcode’s term for warning and error messages emitted when you build your project.
To see the Issue navigator in action, you’ll need to give your code an issue. For example, navigate (as you already know how to do, in at least three different ways) to the file AppDelegate.m, and in the blank line after the last comment at the top of the file’s contents, above the #import line, type howdy. Build the project (Command- B). The Issue navigator will display some error messages, showing that the compiler is unable to cope with this illegal word appearing in an illegal place. Click an issue to see it within its file. In your code, issue “balloons” may appear to the right of lines containing issues; if you’re distracted or hampered by these, toggle their visibility with Editor → Issues → Hide/Show All Issues (Command-Control-M).
Now that you’ve made Xcode miserable, select “howdy” and delete it; build again, and your issues will be gone. If only real life were this easy!
Test navigator (Command-5)
This navigator, new in Xcode 5, lists test files and individual test methods and permits you to run your tests and see whether they succeeded or failed. A test is code that isn’t part of your app; rather, it calls a bit of your app’s code to see whether it behaves as expected.
By default, a new Xcode 5 project has one test file containing one test method, to get you started. I’ll talk more about tests in Chapter 9.
Debug navigator (Command-6)
By default, this navigator will appear when your code is paused while you’re de‐ bugging it. There is not a strong distinction in Xcode between running and de‐ bugging; the milieu is the same. The difference is mostly a matter of whether break‐ points are obeyed (more about that, and about debugging in general, in Chapter 9).
To see the Debug navigator in action, you’ll need to give your code a breakpoint. Navigate once more to the file AppDelegate.m, select in the line that says return YES, and choose Debug → Breakpoints → Add Breakpoint at Current Line to make a blue breakpoint arrow appear on that line. Run the project. By default, as the breakpoint is encountered, the Navigator pane switches to the Debug navigator, and the Debug pane appears at the bottom of the window. This overall layout (Figure 6-4) will rapidly become familiar as you debug your projects.
New in Xcode 5, the Debug navigator starts with two numeric and graphical displays of profiling information (CPU and Memory); click one to see extensive graphical information in the editor. This information allows you to track possible misbehav‐ ior of your app as you run it, without the added complexity of running the Instru‐ ments utility (discussed in Chapter 9). To toggle the visibility of the profiling
The debug layout in Xcode
 information at the top of the Debug navigator, click the “gauge” icon (to the right of the process’s name).
The Debug navigator also displays the call stack, with the names of the nested methods in which a pause occurs; as you would expect, you can click on a method name to navigate to it. You can shorten or lengthen the list with the slider at the bottom of the navigator. The second icon to the right of the process’s name lets you toggle between display by thread and display by queue.
The Debug pane, which can be shown or hidden at will (View → Debug Area → Hide/Show Debug Area, or Command-Shift-Y), consists of two subpanes — the variables list and the console. Either of these can be hidden using the two buttons at the bottom right of the pane. The console can also be summoned by choosing View → Debug Area → Activate Console.
The variables list (on the left)
It is populated with the variables in scope for the selected method in the call stack.
The console (on the right)
Here the debugger displays text messages; that’s how you learn of exceptions thrown by your running app, plus you can have your code deliberately send you log messages describing your app’s progress and behavior. Such messages are important, so keep an eye on the console as your app runs. You can also use the console to enter commands to the debugger. This can often be a better way to explore values during a pause than the variables list.
Viewing a Log in Xcode
 Breakpoint navigator (Command-7)
This navigator lists all your breakpoints. At the moment you’ve only one, but when you’re actively debugging a large project with many breakpoints, you’ll be glad of this navigator. Also, this is where you create special breakpoints (such as symbolic breakpoints), and in general it’s your center for managing existing breakpoints. 
Log navigator (Command-8)
This navigator lists your recent major actions, such as building or running (de‐ bugging) your project. Click a listing to see (in the editor) the log file generated when you performed that action. The log file might contain information that isn’t displayed in any other way, and also it lets you dredge up console messages from the recent past (“What was that exception I got while debugging a moment ago?”).
For example, by clicking on the listing for a successful build, and by choosing to display All and All Messages using the filter switches at the top of the log, we can see the steps by which a build takes place (Figure 6-5). To reveal the full text of a step, click on that step and then click the Expand Transcript button that appears at the far right (and see also the menu items in the Editor menu).
When navigating by clicking in the Navigator pane, modifications to your click can determine where navigation takes place. By default, Option-click navigates in an assis‐ tant pane (discussed later in this chapter), double-click navigates by opening a new window, and Option-Shift-click summons the navigation window, a little heads-up pane where you can specify where to navigate (a new window, a new tab, or a new assistant pane). For the settings that govern these click modifications, see the Navigation pane of Xcode’s preferences. 


Project Window in Xcode


An Xcode project embodies a lot of information about what files constitute the project and how they are to be used when building the app, such as:
  • The source files (your code) that are to be compiled
  • Any .storyboard or .xib files, graphically expressing interface objects to be instan‐ tiated as your app runs
  • Any resources, such as icons, images, or sound files, that are to be part of the app
  • All settings (instructions to the compiler, to the linker, and so on) that are to be obeyed as the app is built
  • Any frameworks that the code will need when it runs
    A single Xcode project window presents all of this information, as well as letting you access, edit, and navigate your code, plus reporting the progress and results of such procedures as building or debugging an app and more. This window displays a lot of information and embodies a lot of functionality! A project window is powerful and elaborate; learning to navigate and understand it takes time. Let’s pause to explore this window and see how it is constructed.
    A project window has four main parts (Figure 6-1): 
    Xcode Project Window


    1. On the left is the Navigator pane. Show and hide it with View → Navigators → Show/ Hide Navigator (Command-0) or with the first View button at the right end of the toolbar.
    2. In the middle is the Editor pane (or simply “editor”). This is the main area of a project window. A project window nearly always displays an Editor pane, and can display multiple Editor panes simultaneously.
    3. On the right is the Utilities pane. Show and hide it with View → Utilities → Show/ Hide Utilities (Command-Option-0) or with the third View button at the right end of the toolbar.
    4. At the bottom is the Debugger pane. Show and hide it with View → Show/Hide Debug Area (Command-Shift-Y) or with the second View button at the right end of the toolbar. 

Wednesday, December 4, 2013

Pointer Parameters and the Address Operator


Objective-C is chock-a-block with pointers (and asterisks), because that’s how Objective-C refers to an object. Objective-C methods typically work with objects, so they typically expect pointer parameters and return a pointer value. But this doesn’t make things more complicated. Pointers are what Objective-C expects, but pointers are also what Objective-C gives you. Pointers are exactly what you’ve got, so there’s no problem.

For example, one way to concatenate two NSStrings is to call the NSString method stringByAppendingString:, which the documentation tells you is declared as follows:
    - (NSString *)stringByAppendingString:(NSString *)aString

This declaration is telling you (after you allow for the Objective-C syntax) that this method expects one NSString* parameter and returns an NSString*. That sounds messy, but it isn’t, because every NSString is really an NSString*. So nothing could be simpler than to obtain a new NSString consisting of two concatenated NSStrings:
    NSString* s1 = @"Hello, ";
    NSString* s2 = @"World!";
    NSString* s3 = [s1 stringByAppendingString: s2];

Sometimes, however, a function or method expects as a parameter a pointer to a thing, but what you’ve got is not that pointer but the thing itself. Thus, you need a way to create a pointer to that thing. The solution is the address operator (K&R 5.1), which is an ampersand before the name of the thing.
For example, there’s an NSString method for reading from a file into an NSString, which is declared like this:
    + (id)stringWithContentsOfFile:(NSString *)path
                          encoding:(NSStringEncoding)enc
                             error:(NSError **)error	
Never mind for now what an id is, and don’t worry about the Objective-C method declaration syntax. Just consider the types of the parameters. The first one is an NSString*; that’s no problem, as every reference to an NSString is actually a pointer to an NSString. An NSStringEncoding turns out to be merely an alias to a primitive data type, an NSUInteger, so that’s no problem either. But what on earth is an NSError**?
By all logic, it looks like an NSError** should be a pointer to a pointer to an NSError. And that’s exactly what it is. This method is asking to be passed a pointer to a pointer to an NSError. Well, it’s easy to declare a pointer to an NSError:
    NSError* err;
But how can we obtain a pointer to that? With the address operator! So our code might look, schematically, like this:
    NSString* path = // something or other
    NSStringEncoding enc = // something or other
    NSError* err = nil;
    NSString* result =[NSString stringWithContentsOfFile: path encoding: enc error: &err];
The important thing to notice is the ampersand. Because err is a pointer to an NSError, &err is a pointer to a pointer to an NSError, which is just what we’re expected to provide. Thus, everything goes swimmingly.
You can use the address operator to create a pointer to any named variable. A C function is technically a kind of named variable, so you can even create a pointer to a function! This is an example of when you’d use the name of the function without the parentheses: you aren’t calling the function, you’re talking about it. For example, &square is a pointer to the square function. Moreover, just as the bare name of an array is implicitly a pointer to its first element, the bare name of a function is implicitly a pointer to the function; the address operator is optional.

Functions


C is a function-based language. A function is a block of code defining what should happen; when other code calls (invokes) that function, the function’s code does happen. A function returns a value, which is substituted for the call to that function.

Here’s a definition of a function that accepts an integer and returns its square:
    int square(int i) {
        return i * i;
}
Now I’ll call that function:
int i = square(3);
Because of the way square is defined, that is exactly like saying:
int i = 9;
That example is extremely simple, but it illustrates many key aspects of functions. Let’s analyze how a function is defined:
int(1) square(2) ((3) int i) {(4)return i * i;
}

Note: The Text in red color is explained below.

(1) We start with the type of value that the function returns; here, it returns an int. 
(2) Then we have the name of the function, which is square.
(3) Then we have parentheses, and here we place the data type and name of any values that this function expects to receive. Here, square expects to receive one value, an int, which we are calling i. The name i (along with its expected data type) is a parameter; when the function is called, its value will be supplied as an argument. If a function expects to receive more than one value, multiple parameters in its definition are separated by a comma (and when the function is called, the arguments supplied are likewise separated by a comma).
(4) Finally, we have curly braces containing the statements that are to be executed when the function is called.


Those curly braces constitute a scope; variables declared within them are local to the function. The names used for the parameters in the function definition are also local to the function; in other words, the i in the first line of the function definition is the same as the i in the second line of the function definition, but it has nothing to do with any i used outside the function definition (as when the result of the function call is assigned to a variable called i). The value of the i parameter in the function definition is assigned from the corresponding argument when the function is called; in the previous example, it is 3, which is why the function result is 9. Supplying a function call with arguments is thus a form of assignment. Suppose a function is defined like this:
    int myfunction(int i, int j) { // ...
And suppose we call that function:
int result = myfunction(3, 4);
That function call effectively assigns 3 to the function’s i parameter and 4 to the func‐
tion’s j parameter.
When a return statement is encountered, the value accompanying it is handed back as the result of the function call, and the function terminates. It is legal for a function to return no value; in such a case, the return statement has no accompanying value, and the definition states the type of value returned by the function as void. It is also legal to call a function and ignore its return value even if it has one. For example, we could say:
square(3);
That would be a somewhat silly thing to say, because we have gone to all the trouble of calling the function and having it generate the square of 3 — namely 9 — but we have done nothing to capture that 9. It is exactly as if we had said:
9;
You’re allowed to say that, but it doesn’t seem to serve much purpose. On the other hand, the point of a function might be not so much the value it returns as other things it does as it is executing, so then it might make perfect sense to ignore its result.

The parentheses in a function’s syntax are crucial. Parentheses are how C knows there’s a function. Parentheses after the function name in the function definition are how C knows this is a function definition, and they are needed even if this function takes no parameters. Parentheses after the function name in the function call are how C knows this is a function call, and they are needed even if this function call supplies no argu‐ ments. Using the bare name of a function is possible, because the name is the name of something, but it doesn’t call the function. (I’ll talk later about something it does do.)
Let’s return to the simple C function definition and call that I used as my example earlier. Suppose we combine that function definition and the call to that function into a single program:
    int square(int i) {
        return i * i;
    }
    int i = square(3);
That is a legal program, but only because the definition of the square function precedes the call to that function. If we wanted to place the definition of the square function elsewhere, such as after the call to it, we would need at least to precede the call with a declaration of the square function (Example 1-3). The declaration looks just like the first line of the definition, but it is a statement, ending with a semicolon rather than a left curly brace.
Example 1-3. Declaring, calling, and defining a function
int square(int i);
int i = square(3);
int square(int i) {
return i * i; }
The parameter names in the declaration do not have to match the parameter names in the definition, but all the types (and, of course, the name of the function) must match. The types constitute the signature of this function. In other words, it does not matter if the first line, the declaration, is rewritten thus:
    int square(int j);
What does matter is that, both in the declaration and in the definition, square is a function taking one int parameter and returning an int. (In a modern Objective-C pro‐ gram, though, the function declaration usually won’t be necessary, even if the function call precedes its definition; see “Modern Objective-C Function and Method Declara‐ tions”)
In Objective-C, when you’re sending a message to an object, you won’t use a function call; you’ll use a method call. But you will most definitely use plenty of C function calls as well. For example, earlier we initialized a CGPoint by setting its x element and its y element, but what you’ll usually do to make a new CGPoint is to call CGPointMake, which is declared like this:
    CGPoint CGPointMake (
       CGFloat x,
CGFloat y );
Despite its multiple lines and its indentations, this is indeed a C function declaration, just like the declaration for our simple square function. It says that CGPointMake is a C function that takes two CGFloat parameters and returns a CGPoint. So now you know (I hope) that it would be legal (and typical) to write this sort of thing:
    CGPoint myPoint = CGPointMake(4.3, 7.1); 

 
 
 

Flow Control and Conditions ( Learn C Programming )


Basic flow control is fairly simple and usually involves a condition in parentheses and a block of conditionally executed code in curly braces. These curly braces constitute a new scope, into which new variables can be introduced. So, for example:
    if (x == 7) {
        int i = 0;
i += 1; }
After the closing curly brace in the fourth line, the i introduced in the second line has ceased to exist, because its scope is the inside of the curly braces. If the contents of the curly braces consist of a single statement, the curly braces can be omitted, but I would advise beginners against this shorthand, as you can confuse yourself. A common be‐ ginner mistake (which will be caught by the compiler) is forgetting the parentheses around the condition. The full set of flow control statements is given, and I’ll just summarize them schematically here (Example 1-1).
Example 1-1. The C flow control constructs
if (condition) { statements;
}
if (condition) { statements;
} else { statements;
}
if (condition) { statements;
} else if (condition) { statements;
} else { statements;


while (condition) { statements;
}
do { statements;
} while (condition);
for (before-all; condition; after-each) { statements;
}

The if...else if...else structure can have as many else if blocks as needed, and the else block is optional. Instead of an extended if...else if...else if...else structure, when the conditions would consist of comparing various values against a single value, you can use the switch statement; be careful, though, as it is rather con‐ fusing and can easily go wrong. The main trick is to re‐ member to end every case with a break statement, unless you want it to “fall through” to the next case (Example 1-2).
Example 1-2. A switch statement
NSString* key;
switch (tag) {
    case 1: { // i.e., if tag is 1
        key = @"lesson";
        break;
    }
    case 2: { // i.e., if tag is 2
        key = @"lessonSection";
break; }
    case 3: { // i.e., if tag is 3
        key = @"lessonSectionPartFirstWord";
        break;
} }
The C for loop needs some elaboration for beginners (Example 1-1). The before-all statement is executed once as the for loop is first encountered and is usually used for initialization of the counter. The condition is then tested, and if true, the block is exe‐ cuted; the condition is usually used to test whether the counter has reached its limit. The after-each statement is then executed, and is usually used to increment or dec‐ rement the counter; the condition is then immediately tested again. Thus, to execute a block using integer values 1, 2, 3, 4, and 5 for i, the notation is:
    int i;
    for (i = 1; i < 6; i++) {
        // ... statements ... 
    }

The need for a counter intended to exist solely within the for loop is so common that C99 permits the declaration of the counter as part of the before-all statement; the declared variable’s scope is then inside the curly braces:
    for (int i = 1; i < 6; i++) {
        // ... statements ...
}
The for loop is one of the few areas in which Objective-C extends C’s flow-control syntax. Certain Objective-C objects, such as NSArray, represent enumerable collections of other objects; “enumerable” basically means that you can cycle through the collection, and cycling through a collection is called enumerating the collection. (I’ll discuss the main enumerable collection types in Chapter 10.) To make enumerating easy, Objective-C provides a for...in operator, which works like a for loop:
    SomeType* oneItem;
    for (oneItem in myCollection) {
        // ... statements ....
    }
On each pass through the loop, the variable oneItem (or whatever you call it) takes on the next value from within the collection. As with the C99 for loop, oneItem can be declared in the for statement, limiting its scope to the curly braces:
    for (SomeType* oneItem in myCollection) {
        // ... statements ....
}
To abort a loop from inside the curly braces, use the break statement. To abort the current iteration from within the curly braces and proceed to the next iteration, use the continue statement. In the case of while and do, continue means to perform imme‐ diately the conditional test; in the case of a for loop, continue means to perform im‐ mediately the after-each statement and then the conditional test.
C also has a goto statement that allows you to jump to a named (labeled) line in your code; even though goto is notoriously “considered harmful,” there are situations in which it is pretty much necessary, especially because C’s flow control is otherwise so primitive. 

   Note It is permissible for a C statement to be compounded of multiple state‐ ments, separated by commas, to be          executed sequentially. The last of the multiple statements is the value of the compound statement as a whole. This construct, for instance, lets you perform some secondary action before each test of a condition or perform more than one after-each action.


We can now turn to the question of what a condition consists of. C has no separate boolean type; a condition either evaluates to 0, in which case it is considered false, or it doesn’t, in which case it is true. Comparisons are performed using the equality and relational operators (K&R 2.6); for example, == compares for equality, and < compares for whether the first operand is less than the second. Logical expressions can be com‐ bined using the logical-and operator (&&) and the logical-or operator (||); using these along with parentheses and the not operator (!) you can form complex conditions. Evaluation of logical-and and logical-or expressions is short-circuited, meaning that if the left condition settles the question, the right condition is never even evaluated.

Warning : Don’t confuse the logical-and operator (&&) and the logical-or opera‐ tor (||) with the bitwise-and operator (&) and the bitwise-or opera‐ tor (|) discussed earlier. Writing & when you mean && (or vice versa) can result in surprising behavior.


The operator for testing basic equality, ==, is not a simple equal sign; forgetting the difference is a common novice mistake. The problem is that such code is legal: simple assignment, which is what the equal sign means, has a value, and any value is legal in a condition. So consider this piece of (nonsense) code:
    int i = 0;
    while (i = 1) {
i = 0; }
You might think that the while condition tests whether i is 1. You might then think: i is 0, so the while body will never be performed. Right? Wrong. The while condition does not test whether i is 1; it assigns 1 to i. The value of that assignment is also 1, so the condition evaluates to 1, which means true. So the while body is performed. Moreover, even though the while body assigns 0 to i, the condition is then evaluated again and assigns 1 to i a second time, which means true yet again. And so on, forever; we’ve written an endless loop, and the program will hang.
C programmers revel in the fact that testing for zero and testing for false are the same thing and use it to create compact conditional expressions, which are considered elegant and idiomatic. Such idioms can be confusing, but one of them is commonly used in Objective-C, namely, in order to test an object reference to see whether it is nil. Since nil is a form of zero, one can ask whether an object s is nil like this:
    if (!s) {
        // ...
}

Objective-C introduces a BOOL type, which you should use if you need to capture or maintain a condition’s value as a variable, along with constants YES and NO (repre‐ senting 1 and 0), which you should use when setting a boolean value. Don’t compare anything against a BOOL, not even YES or NO, because a value like 2 is true in a con‐ dition but is not equal to YES or NO. (Getting this wrong is a common beginner mistake, and can lead to unintended results.) Just use the BOOL directly as a condition, or as part of a complex condition, and all will be well. For example:
    BOOL isnil = (nil == s);
    if (isnil) { // not: if (isnil == YES) 
// ... }