TweetFollow Us on Twitter

Xcode and Code Completion

Volume Number: 19 (2003)
Issue Number: 11
Column Tag: Programming

Getting Started

Xcode and Code Completion

by Dave Mark

This month, we're going to take a look at Xcode's code completion feature. As you'll see, code completion is much like the behavior you see in your browser when you start typing a URL and the browser does its best to save you the keystrokes by filling in the closest match it can to complete the URL. But Xcode's code completion is much more than that. Follow along and you'll see what I mean.

As we've done for the past few months, we'll work with the Sketch sample project. As a reminder, the Sketch files live in /Developer/Examples/AppKit/Sketch/. Before you open Sketch, make a copy of it. We will be breaking it!

Launch Xcode and open your copy of the project Sketch.pbxproj.

Setting Code Completion Prefs

Before we dig into code completion itself, let's take a look at the code completion preferences. Select Preferences... from the Xcode menu, then click on the Navigation icon in the scrolling pane at the top of the Preferences window (Figure 1).


Figure 1. Xcode Preferences, the Navigation Pane.

Your very first course of action is to make sure the Enable Indexing checkbox is checked. The Enable Indexing checkbox tells Xcode to constantly index your project in the background as changes are made. An updated index is what makes project searches so lightning quick. Since the index is maintained in the background, the overhead is hardly noticeable. If you turn indexing off, code completion, search, and anything else that depends on the index will slow considerably. Alternatively, if you have a very large project that was never indexed, you might not want to turn on indexing if you just have a few small changes to make. No sense waiting for the index to be built if you won't be taking advantage of it. In general, I always start off with indexing turned on.

Next step, check the Enable Code Completion checkbox. Obviously, this enables code completion.

There are a series of checkboxes and radio buttons that are enabled once you enable code completion. The first of these, Automatically suggest matching option, is what does the auto-complete as you type. For example, if the constant greenColor was the only symbol in scope that started with a g, you might type g and Xcode might add a grey reenColor.

When there is more than one symbol in scope that matches the current typing, Xcode will build a list of all the matching options. This is called the option list. As you type, if there is more than one matching symbol, Xcode will display a grey ellipsis (...). Anytime you see this ellipsis, you can hit the Code Sense Complete key (see Figure 2 for the Code Sense Complete key binding - the default is F5) and the option list will popup allowing you to select from a list of matching options.

The Automatically popup option list checkbox is a bit of a puzzle to me. The sense I get is that this option controls whether the option list popup appears whenever you start typing a symbol and there is more than one match. If the checkbox is unchecked, you have to type F5 (or whatever the Code Sense Complete key binding is set to) to bring up the popup. If that is the case, then this option is broken, as it behaves the same whether this checkbox is checked or not. I've got a question in to Apple on this, but haven't heard back yet. I'm guessing this is a bug and will be fixed in the next Panther release.

The next item in the prefs dialog is the Tab key selects the current item checkbox. It allows the tab key to both bring up the option list popup and make a selection from the popup. I find this option intuitive. Play with it, both on and off, but I'd definitely leave it checked.

Next is the Contains only items matching word checkbox. If checked, the option list popup will contain only symbols that exactly match what you've typed so far. If it is unchecked, the list will contain matching items and then a few more, either before or after the matching items in the symbol list. Play with this and you'll see what I mean.

Next is a radio button set labeled Option list shows methods/functions as: with buttons for Name only and Name and arguments. This option set lets you specify whether methods/functions listed in the option list popup are listed just by name, or with arguments.

The next radio button set, Completed method/function inserted as:, lets you specify whether the selected method/function is inserted in your code as just the name or with argument placeholders.

    The rest of the Navigation prefs pane lets you determine what types of symbols are included in the editing window's function popup and whether the function popup is sorted alphabetically or by the order the symbols appear in the source file being edited.

We'll take a look at some examples that should make all these options a bit clearer. But first, we'll take a quick look at the key bindings prefs.

Changing the Key Binding

You can change most, if not all of the key bindings that ship with Xcode. Go to the Xcode menu, select Preferences..., then click on the Key Bindings icon. Now click on the Text Key Bindings tab (Figure 2.)


Figure 2. Changing the Code Sense Complete key binding.

The text key bindings are sorted into functional sets, like Text Editing, Cursor Movement, and Text Formatting, each with its own disclosure triangle. Open the Text Editing triangle. Under the c's, you'll find Code Sense Complete. In the Keys column, you should see the key binding F5. To change this to some other key, double-click on the F5. Assuming you are playing with your bindings for the first time, you'll see the dialog shown in Figure 3.


Figure 3. Making a personal copy of the Xcode key binding set.

Click Make Copy to create your own copy of the the Xcode key bindings. I named mine Dave's Bindings. Make all the changes you like to those, then use the popup menu at the top of the pane, labeled Key Binding Sets, to select Xcode Default (See Figure 4), if you ever need to go back to the original settings. You'll also find built-in key sets for BBEdit, CodeWarrior, and MPW.


Figure 4. The key binding sets that ship with Xcode.

The key binding labeled Code Sense Completion List pops up the option list, even if there is only a single item on it. More importantly, the key binding labeled Code Sense Argument Placeholder Select jumps to the next argument placeholder in your just completed code. We'll demo this is a minute.

Add a key binding for this one. Double-click in the Keys column to the right of Code Sense Argument Placeholder Select. When the edit field appears, type in your key binding. Most folks use control-slash (^/) for this one.

Taking Code Completion For A Spin

Let's take a quick look at code completion in action. I'm editing the file SKTGraphic.m in the Sketch project. Remember to make a copy of the project before you mess around with it, just so you don't break it.

I'm going to add this line of code to the project:

[self setBounds:NSMakeRect(0.0, 0.0, 1.0, 1.0)];

Since we're not concerned with compiling this code, feel free to type this line anywhere you like. Start at the beginning of a new line by typing the beginning of the line:

 [self setBounds:NSMake

Note that I typed NSM in all caps, as opposed to nsm. This is because I have the Matches using case-sensitivity checkbox checked in the Navigation prefs.

Figure 5 shows where we are at this point. Notice the ellipsis (...) that follows the NSMake, telling us that there are some matching options. If there was only one, the option would be filled in in grey.


Figure 5. The start of NSMakeRect code completion.

Now press F5 or tab to bring up the option list popup. Figure 6 shows the popup with the Contains only items matching word checkbox checked. I pressed the arrow key twice to select NSMakeRect, then pressed tab to add NSMakeRect, and its argument placeholders, in the code.


Figure 6. The option list popup for NSMake.

Here's the code at this point:


Note that each argument is marked by a placeholder between matching angle brackets and pound signs. The four arguments are x, y, w, and h. The first placeholder is selected. I want the first argument to be 0.0. I type it, then press control-slash (^/) to select the next placeholder:


I continue typing arguments and pressing ^/ until my statement is complete:


Till Next Month...

I really like this method of argument selection. It works well for me. As you've seen over the last few months, the move from Project Builder to Xcode is a quantum leap forward. I really like the attention to detail, such as the depth of preference settings on the Code Sense and Key Bindings panes. And you just know that as much as compilation performance has improved from Project Builder to Xcode, there are dramatic improvements still to come...


Dave Mark is a long-time Mac developer and MacTech contributor. Author of more than a dozen books on various Mac-development topics, Dave is all about Xcode these days. Last month's column took the debugger through a few of its paces. This month's installment will focus on code completion.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Monolingual 1.6.4 - Remove unwanted OS X...
Monolingual is a program for removing unnecesary language resources from OS X, in order to reclaim several hundred megabytes of disk space. If you use your computer in only one (human) language, you... Read more
CleanApp 5.0 - Application deinstaller a...
CleanApp is an application deinstaller and archiver.... Your hard drive gets fuller day by day, but do you know why? CleanApp 5 provides you with insights how to reclaim disk space. There are... Read more
Fantastical 2.0 - Create calendar events...
Fantastical is the Mac calendar you'll actually enjoy using. Creating an event with Fantastical is quick, easy, and fun: Open Fantastical with a single click or keystroke Type in your event details... Read more
Cocktail 8.2 - General maintenance and o...
Cocktail is a general purpose utility for OS X that lets you clean, repair and optimize your Mac. It is a powerful digital toolset that helps hundreds of thousands of Mac users around the world get... Read more
Direct Mail 4.0.4 - Create and send grea...
Direct Mail is an easy-to-use, fully-featured email marketing app purpose-built for OS X. It lets you create and send great looking email campaigns. Start your newsletter by selecting from a gallery... Read more
jAlbum Pro 12.6 - Organize your digital...
jAlbum Pro has all the features you love in jAlbum, but comes with a commercial license. With jAlbum, you can create gorgeous custom photo galleries for the Web without writing a line of code!... Read more
jAlbum 12.6 - Create custom photo galler...
With jAlbum, you can create gorgeous custom photo galleries for the Web without writing a line of code! Beginner-friendly, with pro results Simply drag and drop photos into groups, choose a design... Read more
Lyn 1.5.9 - Lightweight image browser an...
Lyn is a lightweight and fast image browser and viewer designed for photographers, graphic artists and Web designers. Featuring an extremely versatile and aesthetically pleasing interface, it... Read more
Sublime Text 3080 - Sophisticated text e...
Sublime Text is a sophisticated text editor for code, markup, and prose. You'll love the slick user interface, extraordinary features, and amazing performance. Goto Anything. Use Goto Anything to... Read more
WALTR 1.0.11 - Drag-and-drop any media f...
WALTR is designed to make it easy to upload and convert any music or video file to an iPad or iPhone format for native playback. It supports a huge variety of media file types, including MP3, MP4,... Read more

Bio Inc's New Expansion is Infectin...
Bio Inc., by DryGin Studios, is the real time strategy game where you infect a human body with the worst virus your evil brain can design. Recently, the game was updated to add a whole lot of new features. Now you can play the new “Lethal”... | Read more »
The Monocular Minion is Here! Despicable...
Despicable Me: Minion Rush, by Gameloft, is introducing a new runner to the mix in their latest update. Now you can play as Carl, the prankster minion. Carl has a few new abilities to play with, including running at a higher speed from the start.... | Read more »
Dungeon of Madness (Games)
Dungeon of Madness 1.0.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0.0 (iTunes) Description: Dungeon of Madness is an action game where you rotate tiles to create our own route. Help the hero by connecting the... | Read more »
Filters for iPhone (Photography)
Filters for iPhone 1.0 Device: iOS iPhone Category: Photography Price: $.99, Version: 1.0 (iTunes) Description: | Read more »
Jump'N'Shoot Attack (Games)
Jump'N'Shoot Attack 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: A mobile game for gamers! Join Louise Lightfoot, the legendary "Master of Jumping and Shooting", on her mission to save... | Read more »
Space Bounties Inc. (Games)
Space Bounties Inc. 1.4 Device: iOS Universal Category: Games Price: $1.99, Version: 1.4 (iTunes) Description: SuperGameDroid: 4/5 "Satisfying futuristic RPG combat, high replay value, and a heavy dose of nostalgia make Space... | Read more »
Gamebook: Pocket RPG (Games)
Gamebook: Pocket RPG 1.0.11 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.11 (iTunes) Description: Walk into the Land of Lanthir Lamath ruled by wicked skeletons and fight for your life in a thrilling adventure.... | Read more »
Kids Can Mix, Match, and Catch with Tata...
Tatadada MixMatch, by Tatadada Ltd, is a mobile version of the classic game of mix & match. The game uses brightly colored creatures to train your children's pattern matching skills and hand-eye coordination. It's aimed at children around age 5... | Read more »
The Trace: Murder Mystery Game (Games)
The Trace: Murder Mystery Game 1.2.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.2.0 (iTunes) Description: | Read more »
This Week at 148Apps: March 16-20, 2015
Spring Roars In At 148Apps How do you know what apps are worth your time and money? Just look to the review team at 148Apps. We sort through the chaos and find the apps you're looking for. The ones we love become Editor’s Choice, standing out above... | Read more »

Price Scanner via MacPrices.net

Logitech Says MX Master Is Its Most Advanced...
Logitech’s new MX Master Wireless Mouse incorporates the best of Logitech’s many computer mouse innovations into a striking hand-sculpted design. The company claims that the MX Master creates a new... Read more
Save up to $300 on a new Mac, $30 on an iPad,...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
Apple refurbished 2014 MacBook Airs available...
The Apple Store lowered prices on Apple Certified Refurbished 2014 MacBook Airs recently, with models now available starting at $679. An Apple one-year warranty is included with each MacBook, and... Read more
Mac Notebook Evolution; A Desktop Replacement...
More often than not right from the beginning, Apple’s Macs have tended to skew toward small. The original Macs were called “compacts,”, and notwithstanding a few exceptions like the honking Big Mac... Read more
13-inch 1.4GHz/128GB MacBook Air (Apple refur...
The Apple Store has Apple Certified Refurbished 2014 13″ 1.4GHz/128GB MacBook Airs available for $759 including free shipping plus Apple’s standard one-year warranty. Their price is $240 off original... Read more
YEP! Alternative Browser for iOS Now Supports...
Pfaeffikon, Switzerland based Power App AG has announced the release of an update to their Yep! Web Browser (v1.3.0) for iOS8 iPhone and iPad. Yep! hit the App Store shortly after the release of iOS... Read more
15-inch Retina MacBook Pros on sale for up to...
B&H Photo has the new 2014 15″ Retina MacBook Pros on sale for up to $250 off MSRP for a limited time. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $... Read more
Clearance 13-inch Retina MacBook Pros availab...
B&H Photo has leftover 2014 13″ Retina MacBook Pros on sale for up to $250 off original MSRP. Shipping is free, and B&H charges NY sales tax only: - 13″ 2.6GHz/128GB Retina MacBook Pro: $1098... Read more
Clearance 2014 MacBook Airs on sale for up to...
B&H Photo has MacBook Airs on sale for up to $180 off original MSRP. Shipping is free, and B&H charges NY sales tax only: - 11″ 128GB MacBook Air: $789.99 110 off original MSRP - 11″ 256GB... Read more
Apple refurbished Time Capsules available for...
The Apple Store has certified refurbished Time Capsules available for $100 off MSRP. Apple’s one-year warranty is included with each Time Capsule, and shipping is free: - 2TB Time Capsule: $199, $100... Read more

Jobs Board

*Apple* Solutions Consultant - Retail Sales...
**Job Summary** As an Apple Solutions Consultant (ASC) you are the link between our customers and our products. Your role is to drive the Apple business in a retail Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - D...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Systems Engineer - Pre Sales, Educat...
…is responsible for proactively providing technical expertise to drive sales of Apple solutions into assigned accounts. The SE architects, validates, and assists in Read more
Sr. Technical Services Consultant, *Apple*...
**Job Summary** Apple Professional Services (APS) has an opening for a senior technical position that contributes to Apple 's efforts for strategic and transactional Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.