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

Latest Forum Discussions

See All

Jump into one of Volkswagen's most...
We spoke about PUBG Mobile yesterday and their Esports development, so it is a little early to revisit them, but we have to because this is just too amusing. Someone needs to tell Krafton that PUBG Mobile is a massive title because out of all the... | Read more »
PUBG Mobile will be releasing more ways...
The emergence of Esports is perhaps one of the best things to happen in gaming. It shows our little hobby can be a serious thing, gets more people intrigued, and allows players to use their skills to earn money. And on that last point, PUBG Mobile... | Read more »
Genshin Impact 5.1 launches October 9th...
If you played version 5.0 of Genshin Impact, you would probably be a bit bummed by the lack of a Pyro version of the Traveller. Well, annoyingly HoYo has stopped short of officially announcing them in 5.1 outside a possible sighting in livestream... | Read more »
A Phoenix from the Ashes – The TouchArca...
Hello! We are still in a transitional phase of moving the podcast entirely to our Patreon, but in the meantime the only way we can get the show’s feed pushed out to where it needs to go is to post it to the website. However, the wheels are in motion... | Read more »
Race with the power of the gods as KartR...
I have mentioned it before, somewhere in the aether, but I love mythology. Primarily Norse, but I will take whatever you have. Recently KartRider Rush+ took on the Arthurian legends, a great piece of British mythology, and now they have moved on... | Read more »
Tackle some terrifying bosses in a new g...
Blue Archive has recently released its latest update, packed with quite an arsenal of content. Named Rowdy and Cheery, you will take part in an all-new game mode, recruit two new students, and follow the team's adventures in Hyakkiyako. [Read... | Read more »
Embrace a peaceful life in Middle-Earth...
The Lord of the Rings series shows us what happens to enterprising Hobbits such as Frodo, Bilbo, Sam, Merry and Pippin if they don’t stay in their lane and decide to leave the Shire. It looks bloody dangerous, which is why September 23rd is an... | Read more »
Athena Crisis launches on all platforms...
Athena Crisis is a game I have been following during its development, and not just because of its brilliant marketing genius of letting you play a level on the webpage. Well for me, and I assume many of you, the wait is over as Athena Crisis has... | Read more »
Victrix Pro BFG Tekken 8 Rage Art Editio...
For our last full controller review on TouchArcade, I’ve been using the Victrix Pro BFG Tekken 8 Rage Art Edition for PC and PlayStation across my Steam Deck, PS5, and PS4 Pro for over a month now. | Read more »
Matchday Champions celebrates early acce...
Since colossally shooting themselves in the foot with a bazooka and fumbling their deal with EA Sports, FIFA is no doubt scrambling for other games to plaster its name on to cover the financial blackhole they made themselves. Enter Matchday, with... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra available today at Apple fo...
Apple has several Certified Refurbished Apple Watch Ultra models available in their online store for $589, or $210 off original MSRP. Each Watch includes Apple’s standard one-year warranty, a new... Read more
Amazon is offering coupons worth up to $109 o...
Amazon is offering clippable coupons worth up to $109 off MSRP on certain Silver and Blue M3-powered 24″ iMacs, each including free shipping. With the coupons, these iMacs are $150-$200 off Apple’s... Read more
Amazon is offering coupons to take up to $50...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for up to $110 off MSRP, each including free delivery. Prices are valid after free coupons available on each mini’s product page, detailed... Read more
Use your Education discount to take up to $10...
Need a new Apple iPad? If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $100 off the... Read more
Apple has 15-inch M2 MacBook Airs available f...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
Mac Studio with M2 Max CPU on sale for $1749,...
B&H Photo has the standard-configuration Mac Studio model with Apple’s M2 Max CPU in stock today and on sale for $250 off MSRP, now $1749 (12-Core CPU and 32GB RAM/512GB SSD). B&H offers... Read more
Save up to $260 on a 15-inch M3 MacBook Pro w...
Apple has Certified Refurbished 15″ M3 MacBook Airs in stock today starting at only $1099 and ranging up to $260 off MSRP. These are the cheapest M3-powered 15″ MacBook Airs for sale today at Apple.... Read more
Apple has 16-inch M3 Pro MacBook Pro in stock...
Apple has a full line of 16″ M3 Pro MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $440 off MSRP. Each model features a new outer case, shipping is free, and an... Read more
Apple M2 Mac minis on sale for $120-$200 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $110-$200 off MSRP this weekend, each including free delivery: – Mac mini M2/256GB SSD: $469, save $130 – Mac mini M2/512GB SSD: $689.... Read more
Clearance 9th-generation iPads are in stock t...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on clearance sale for starting at only $199 on their online store for a limited time. Sale prices for online orders only, in-store prices may vary... Read more

Jobs Board

Senior Mobile Engineer-Android/ *Apple* - Ge...
…Trust/Other Required:** NACI (T1) **Job Family:** Systems Engineering **Skills:** Apple Devices,Device Management,Mobile Device Management (MDM) **Experience:** 10 + Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Full Time (80 hrs/pay period) Evenings General Summary Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.