Using the Xcode Source Editor
Over the past few hours, you have learned how to create projects, add files, add frameworks, and do much of the work necessary to successfully build you own application projects. What we have not touched on, however, is the Xcode Source Editor itself, which you use to edit, unsurprisingly, source code. You’ve got your project and files; now how about editing them?
This hour walks through the different Source Editor features—from automatic code completion to code refactoring. You learn how the Source Editor can help you write clean, well-formatted code and even identify problems before you even try to run your application. Even if you have played around with editing files already, you’re still likely to find a few undiscovered tricks in this hour.
Understanding Editor Basics
Let’s be serious: If you’re learning how to program in Xcode, you know how to edit a text file. I am not going to bore you with details on how to move your cursor or copy and paste. The Xcode Source Editor works just like any text editor, with several additions that may make your life easier. To follow along with this hour’s lesson, create a new project called HelloXcode using the Mac OS X Cocoa Application template and the configuration shown in Figure 6.1. We’ll edit this so that it displays a simple message (Hello Xcode) in the application’s window. Nothing earth shattering, but you’ll find it handy to keep this open so that you can test the tools as you read.
FIGURE 6.1 Create a new Mac OS X Cocoa application.
To edit code in Xcode, use the Project Navigator to find the file you want to work on, and then click the filename. The editable contents of the file are shown in the Editor area of the Xcode interface. For our sample application, click the AppDelegate.m file, as shown in Figure 6.2.
Code Completion
Using the Source Editor, start entering the following text to implement the applicationDidFinishLaunching method. Start a new line immediately following the existing comment “Insert code here to initialize your application.” Update the method as shown in Listing 6.1.
LISTING 6.1 A Short Sample Mac OS X Application
1:
- (void
)applicationDidFinishLaunching:(NSNotification
*)aNotification2:
{3:
// Insert code here to initialize your application
4:
NSTextField *myMessage;5:
NSTextField *myUnusedMessage;6:
myMessage=[[NSTextField
alloc
]init
];7:
myMessage.font
=[NSFont
systemFontOfSize
:72.0
];8:
myMessage.stringValue
=@"Hello Xcode"
;9:
myMessage.textColor
=[NSColor
blueColor
];10:
myMessage.editable
=NO
;11:
[self
.window
setContentView
:myMessage];12:
}
FIGURE 6.2 Choose a file to edit.
As you enter the code, notice that when you are typing a method or class name that Xcode recognizes, a pop-up dialog appears near your cursor, as shown in Figure 6.3. Here, the systemFontOfSize method is being typed, and Xcode is presenting potential options for autocompletion as I type.
To choose an autocompletion value, use the arrow keys to highlight the value you want to use, and then press Return to insert it into your code. You can also press Escape to make the pop-up disappear.
If you are completing a method name, chances are that you need to provide parameters as well. (In the case of systemFontOfSize, it is a floating-point value that describes the size of the text.) You can again use the arrow keys to move between the parameter fields and enter the values you want, or you can just press Tab to skip from parameter to parameter.
FIGURE 6.3 Xcode autocompletes recognized methods, classes, and symbols.
Auto-Indentation
Clean code is easier to read and easier to maintain, and Xcode works behind the scenes to keep your code nicely formatted through auto-indention. As you program, Xcode automatically indents lines so that they fall either directly under the previous line or as appropriate to the structure of the statements you are writing.
Code within conditional blocks and loops, for example, are indented farther than surrounding code to visually show that they are a cohesive block. This has no effect on execution, but it can make reading through a source code file much easier than if each line’s code starts at the first character.
You can control the logic for the Xcode auto-indentation system using the Text Editing panel of the application preferences (Xcode, Preferences) and the Indentation button within that, as shown in Figure 6.4.
FIGURE 6.4 Configure the Xcode indentation logic.
A nice feature of Xcode is that indentation isn’t just applied while you’re typing and then lost. Although you can certainly move your code around and make it into a mess, you can always apply the indentation rules again, as follows:
- Within the sample project, add tabs and spaces in front of some of the lines in applicationDidFinishLaunching.
- Delete the indentation from some of the lines, as well.
- After you have made the method sufficiently ugly in appearance, select the lines of code.
- Choose Editor, Structure, Re-Indent (Control+I).
Xcode reformats the code, and all is well again, as shown in Figure 6.5.
FIGURE 6.5 Before and after applying the indentation logic.
Balancing Delimiters
Indentation may be “just for looks,” but delimiters are not. Properly balanced delimiters are the difference between code that works the way you want and code that seems to have a mind of its own. When coding in Objective-C, you work with three primary types of block delimiters:
- () Parentheses for function calls
- [] Square brackets for Objective-C messaging
- {} Curly brackets for logical programming blocks
Each time you type one of these delimiters, you need another matching one added to your code. If you happen to miss one or put one in the wrong place, chances are your code won’t run. Worse yet, it might run and not do what you expect.
To help you keep track of where your delimiters are (or aren’t) balanced, Xcode automatically highlights the first delimiter when you type the second (or move the cursor to the immediate right of the second delimiter).
For example, return to the sample method that you wrote earlier (applicationDidFinishLaunching), position your text entry cursor immediately before the right curly bracket, }, at the end of the method. Next, press the right arrow to move the text cursor to the right of the curly bracket. As you do this, notice that the left curly bracket, {, at the start of the method is briefly highlighted. This same behavior occurs with parentheses and square brackets, too.
To select all of the code that is contained within a set of delimiters, right-click within the code, and then choose Structure, Balance Delimiter (also available from the Editor menu), as shown in Figure 6.6.
FIGURE 6.6 Select the code between two delimiters.
Code Folding
Working in conjunction with your code delimiters and the logical blocks/methods you define in your code, Xcode’s code-folding features let you focus on editing a specific piece of code and hide the rest. To the immediate right of your Editor is the gutter, which typically holds line numbers (enabled in Xcode’s Text Editing preferences) and error/warning icons. The very right side of the gutter is the code-folding ribbon. By clicking in the ribbon, you can fold (collapse) your methods and functions and comment blocks.
For example, view the code in the applicationDidFinishLaunching method. Click immediately to the left of the method in the code-folding ribbon. The code collapses and is replaced with an ellipsis (...), as shown in Figure 6.7. You can expand the code again by double-clicking the ellipsis or by using the disclosure arrow that appears in the ribbon.
FIGURE 6.7 Collapse your code to improve your focus.
You can quickly collapse all comment blocks (text between /* and */) and function/methods using the Editor, Code Folding menu.
The Other Bits
As with any application, some settings and options (although useful to some) do not warrant a full discussion. The Xcode Source Editor has a number of other features that might come in handy but that do not necessarily pertain to the editing process itself.
What follows are a few configuration tweaks and editing functions that you might want to use in your projects.
Line Numbers
To enable or disable the display of line numbers beside your code, use the Line Numbers check box accessed within the Text Editing section of Xcode preferences. Line numbers are a great help when debugging code or describing your code to other developers.
Edit All in Scope
If you’ve ever written a function or method only to smack yourself in the head and say, “I should have named that variable something else,” you will love the Edit All in Scope feature. To simultaneously change all the instances of a variable name within a method, select the variable name, and then choose Editor, Edit All in Scope (Control+Command+E). Each instance of the variable highlights, and all update as you edit one, as shown in Figure 6.8.
FIGURE 6.8 Quickly change symbol names using Edit All in Scope.
Shift, Move, or Comment
The Structure contextual menu (also accessible from the Editor menu) contains commands for shifting (indenting/outdenting) your code left or right, moving it up or down, or commenting it out. Use these functions to quickly act on a selection of lines, rather than changing each one individually.
Hide/Show Invisibles
There’s more to your code than you can see. To get a glimpse at how the code is formatted (tabs/spaces/return characters) or check for any gremlins that may have crept into your code from pasting from other applications, use the Editor, Show Invisibles command. This displays all normally invisible characters directly within your code listing. To hide the characters, choose Editor, Hide Invisibles.
Syntax Coloring
Normally, Xcode colors your code based on the type of file you are editing. You can override the chosen syntax-highlighting scheme by choosing Editor, Syntax Coloring from the menu. You can also change the syntax colors entirely using the Xcode Fonts & Colors preferences, shown in Figure 6.9.
FIGURE 6.9 Change the syntax color rules to suit your sensibilities.