Hidden Features of Xcode

Viewed 240555

With a huge influx of newbies to Xcode, I'm sure there are lots of Xcode tips and tricks to be shared.

What are yours?

89 Answers

Switch to Header/Source File

  • Option ⌥ Command ⌘ Up Arrow ↑

  • View > Switch to Header/Source File

Switches between the .m and .h files.

  • In Xcode 4 this is ctrl Command ⌘ Up Arrow ↑

⌘ Command + Double-Click on a symbol: Jump to Definition of a symbol.

⌥ Option + Double-Click on a symbol: Find Text in Documentation of a symbol. (Only works if you have they symbol's Doc Set installed.)

Favorites Bar:

Favorites bar is just like you have in Safari for storing - well - favorites. I often use it as a place to store shortcuts (which you can do by drag-dropping) to files I am using right now. Generally this is more useful when I'm working with a large or unfamiliar project.

To show the Favorites Bar, select the following menu option:

  • View > Layout > Show Favorites Bar

Auto-completion Keyboard Shortcuts

Tab ⇥ OR Control ⌃ /: Select the next auto-completion argument.

Shift ⇧ Tab ⇥ OR Shift ⇧ Control ⌃ /: Select the previous auto-completion argument.

Escape ⎋: Shows the auto completion pop-up list.

Turn off the "undo past the last point" warning

When you attempt to undo after saving, you will get the following prompt:

"You are about to undo past the last point this file was saved. Do you want to do this?"

To get rid of this warning, enter the following into a terminal window:

defaults write com.apple.Xcode XCShowUndoPastSaveWarning NO

Change the company name in template files

Paste this into the Terminal application:

defaults write com.apple.Xcode PBXCustomTemplateMacroDefinitions '{"ORGANIZATIONNAME" = "Microsoft";}'

Change "com.yourcompanyname" in all your templates:

  1. Find the directory: /Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Project Templates/Application
  2. Use your favourite multi-file search-and-replace tool to change com.yourcompany to whatever value you normally use to build for a device. I used BBEdit's multi-find-and-replace after I opened the whole directory. You should be replacing the value in all the info.plist files. I found 8 files to change. The number of times a build has failed because I forgot to change this string is ridiculous.

Quickly jump to a Group in the Groups and Files pane

  • Control ⌃ Option ⌥ Shift ⇧ + <First letter of a Group name>

If you hold down the three keys above, you can quickly jump to groups in the left (Groups and Files) page by pressing the first letter of a groups name. For example, Control ⌃Option ⌥Shift ⇧T takes you to Targets and Control ⌃Option ⌥Shift ⇧S to Source. Press it again and it jumps to SCM. Sometimes it takes several tries for this to work (I don't know why).


Cycling between autocompletion choices

  • Control ⌃ .

  • Shift ⇧ Control ⌃ .: Cycles backwards between autocompletion choices.

Control ⌃. (Control-Period) after a word automatically accepts the first choice from the autocompletion menu. Try typing log then Control ⌃. and you'll get a nice NSLog statement. Press it again to cycle through any choices. To see all the mutable choices, type NSMu then Control ⌃..


Quick Help

  • Control ⌃ Command ⌘ ? (While your cursor is in the symbol to look up)

  • Option ⌥ + <Double-click a symbol>

  • Help > Quick Help

To get to the documentation from the Quick Help window, click the book icon on the top right.


See the documentation for a symbol

  • Command ⌘ Option ⌥ + <Double-click a symbol>

Takes you straight to the full documentation.


Make non-adjacent text selections

  • Command ⌘ Control ⌃ + <Double-click in the editor>

Use the above shortcut for a strange way of selecting multiple words. You can make selections of words in totally different places, then delete or copy them all at once. Not sure if this is useful. It's Xcode only as far as I can tell.


Use Emacs key bindings to navigate through your code

This trick works in all Cocoa application on the Mac (TextEdit, Mail, etc.) and is possibly one of the most useful things to know.

  • Command ⌘ Left Arrow or Command ⌘ Right Arrow Takes you to the beginning and end of a line.
  • Control ^ a and Control ^ e Do the same thing
  • Control ^ n and Control ^ p Move the cursor up or down one line.
  • Control ^ f and Control ^ b Move the cursor back or forward one space

Pressing Shift ⇧ with any of these selects the text between move points. Put the cursor in the middle of a line and press Shift ⇧ Control ^ e and you can select to the end of the line.

Pressing Option ⌥ will let you navigate words with the keyboard. Option ⌥ Control ^ f skips to the end of the current word. Option ⌥ Control ^ b skips to the beginning of the current word. You can also use Option ⌥ with the left and right arrow keys to move one-word-at-a-time.

  • Control ^ Left Arrow and Control ^ Right Arrow moves the cursor between camel-cased parts of a word.

Try it with NSMutableArray. You can quickly change it to NSArray by putting your cursor after the NS, pressing Shift ⇧ Control ^ Right Arrow then Delete.

Open Quickly...

  • Command ⌘ Shift ⇧ D

  • File > Open Quickly...

I'm a big fan of the Open Quickly feature, which is particularly good in Xcode 3.1 and later. When you want to open a file or a symbol definition that's in your project or in a framework, just hit the keyboard shortcut, type a bit of the file or symbol's name, use Up Arrow ↑ and Down Arrow ↓ to pick to the right result (if need be), and then hit Return ↩ to open the file or navigate to the symbol definition.

On Xcode 4:

  • Command ⌘ Shift ⇧ o

Open Quickly uses the current word as a search term

Also, something I didn't know about Xcode until two minutes ago (when schwa pointed it out in a comment) is that, if the editor's text caret is inside of a word when Open Quickly is invoked, that word will be used as the Open Quickly search term.

Use #pragma for organization

You can use:

#pragma mark Foo

... as a way to organize methods in your source files. When browsing symbols via the pop up menu, whatever you place in Foo will appear bold in the list.

To display a separator (i.e. horizontal line), use:

#pragma mark -

It's very useful, especially for grouping together delegate methods or other groups of methods.

1. Breakpoint on "objc_exception_throw"

You should always have a breakpoint on objc_exception_throw.

2. Debugging retain/release problems with "Zombie" variables

Use the following code:

NSZombieEnabled = YES;
NSDeallocateZombies = NO;

... to debug retain and release problems. For more information, see the "Finding Memory Leaks" section of Apple's Debugging Applications document.

3. Jumping to a class in Xcode from Interface Builder

Command ⌘ + Double-click on an object in Interface Builder's Document Window to jump to that class in Xcode. This is very handy with File's Owner.

4. Reusing customized objects in Interface Builder

Drag a customized object back to Interface Builder's Library for later reuse.

5. Select overlapping items in Interface Builder

Control ⌃ Shift ⇧ + Click on an object in Interface Builder to see a menu of all of the objects under the mouse.

6. Interface Builder Gesture Guide

Interface Builder Gesture Guide.

Ctrl + 2: Access the popup list of methods and symbols in the current file.

This is super useful because with this shortcut you can navigate through a file entirely using the keyboard. When you get to the list, start typing characters and the list will type-select to the symbol you are looking for.

Zoom Editor In

If your window displays both the detail and editor view, you can zoom the editor in to expand the editor view to the full height of the window. (This is fairly easily found, but many seem to overlook it.)

You can do this by using one of the following methods:

  • Command ⌘ Shift ⇧ E

  • View > Zoom Editor In

  • Drag the splitter (between the editor window and the file list above it) upwards.

Not much of a keyboard shortcut but the TODO comments in the source show up in the method/function dropdown at the top of the editor.

So for example:

// TODO: Some task that needs to be done.

shows up in the drop down list of methods and functions so you can jump to it directly.

Most Java IDEs show a marker for these task tags in the scrollbar, which is nicer, but this also works.

⌘-[ and ⌘-] to indent and unindent selected text. Makes cleaning up source code much easier.

Hold Option while splitting windows to split vertically rather than horizontally.

Double-click on the square brackets or parentheses to obtain bracket and parentheses matching.

Control Xcode's text editor from the command line: xed

> xed -x                # open a new untitled document
> xed -xc foo.txt       # create foo.txt and open it
> xed -l 2000 foo.txt   # open foo.txt and go to line 2000

# set Xcode to be your EDITOR for command line tools
# e.g. for subversion commit
> echo 'export EDITOR="xed -wcx"' >> ~/.profile

> man xed               # there's a man page, too

"Ctrl+Left/Right Arrow" to do intra-word text navigation. I use this feature to jump the cursor from the one "camel hump" in a variable to the next.

Xcode supports text macros that can be invoked via the Insert Text Macro menu at the end of the Edit menu. They can also be invoked using Code Sense, Xcode's code completion technology.

For example, Typing the key sequence p i m control-period will insert #import "file" into your code, with file as an editable token just like with code completion.

Right click on a variable in your function and click edit all in scope. Been using it a lot since I found this out.

ctrl T

Debugging - how to use GDB

Being new to this still, I find trapping and identifying faults a rather daunting job. The console, despite it being a powerful tool, usually does not yield very intuitive results and knowing what you are looking at in the debugger can be equally difficult to understand. With the help of some of they guys on Stack Overflow and the good article about debugging that can be found at Cocoa With Love it becomes a little more friendly.

Navigate among open files back and forth:
⌥⌘←
⌥⌘→

Technically an Interface Builder tip, but they're a book-matched pair, so I don't think this is off topic...

Shift + Right Click on one of your controls and you get a nice pick list of the object hierarchy. No more click, click, click, frustration!

With Trackpad:

  • Swipe Three Fingers Up - Switch between header and source file, which is easier than Cmd + Opt + Up;
  • Swipe three fingers down - Switch between declaration and definition when selecting a class or method, found these two kind currently;
  • Swipe three fingers left - Go back (Cmd + Opt + Left);
  • Swipe three fingers right - Go forward (Cmd + Opt + Right);

Tested with Xcode 3.2.5.

The class browser in Xcode! Reached by pressing shift + + c. You can reduce the scope to only show your active project. It gives you a less cluttered view as long as you only want to browse the class hierarchy.

Using ] to automatically insert [ in the correct location

I come from a .NET background, so I'm used to typing a symbol and then typing one of its method names. So I always forget to include the [ before I start typing the object name. Usually this meant I would need to go to the beginning of the line and add the [ manually. I didn't realize I could just press ] at the current cursor position, and it will be added automatically.

There are ways to use this: either after typing the function's name, or right before typing the function's name.

Method 1: after the function name

myObject testMethod]

... becomes:

[myObject testMethod]

... with the caret positioned after the ].

Method 2: before the function name

myObject]

... becomes:

[myObject ]

... with the caret positioned right before the ].

The advantage of the latter (2) is that code completion will filter on the methods of your object. Whereas with the former (1) if you try to invoke code completion immediately after myObject, it won't be filtered. Another advantage to (2) is it behaves more like other programming languages that use dot notation. You type the name of the object then simply ] instead of . to access a method.

Select a block of text and type cmd-/ to comment it out. Do it again to remove the comments characters.

This is especially useful when combined with brace-matching by double-clicking on balanced chars (parens, braces, brackets).

ctrl + alt + + r to clear the log

When using Code Sense with many keyboards, use control + , to show the list of available completions, control + . to insert the most likely completion, and control + / & shift + control + / to move between placeholder tokens. The keys are all together on the keyboard right under the home row, which is good for muscle memory.

Use the Class Browser to show inherited methods

Apple's API reference documentation does not show methods inherited from a superclass. Sometimes, though. it's useful to be able to see the full range of functionality available for a class -- including a custom class of your own. You can use the Class Browser (from the Project menu) to display a flat or hierarchical list of all the classes related to a current project. The upper pane on the right hand side of the browser window shows a list of methods associated with the object selected in the browser. You can use the Configure Options sheet to select "Show Inherited Members" to show inherited methods as well as those defined by the selected class itself. You click the small book symbol to go to the corresponding documentation.

Might go without saying, but if you want to use intra-word navigation, make sure you change the key presets in for Spaces (in the Expose & Spaces preference pane), if you use it.

I switched Spaces to use Ctrl-Option Left/Right.

Edit: To set Spaces to Ctrl-Option Left/Right, select the "To switch between spaces:" popup and hold down the Option key. The first item will change from Ctrl Arrow Keys to Ctrl-Option Arrow Keys.

Cmd-/ to automatically insert "//" for comments. Technically the same number of keystrokes, but it feels faster...

Also the default project structure is to put resources and class files in separate places. For larger amounts of code create logical groups and place related code and xib files together. Groups created in XCode are just logical structures and do not change where your files are on disk (though you can set them up to replicate a real directory structure if you wish)

pragma mark

Example:

#pragma mark === Initialization ===

Writing this line above all initialization methods will generate a nice heading in the dropdown menu above the editor.

Open Quickly

Shift + cmd + D Start typing a file name you'd like to open. Very cool if you look for framework headers. They have nice comments too, sometimes additional info to the docs.

ESC

When your text-cursor is on a uncomplete method name for example, press ESC. It will shop up everything that might fit in there, and you can quickly complete very large method names. It's also good if you can't remember exactly the name of a method. Just press ESC.

I think these are the best ones I know until now.

(Migrated from deleted question by Stack Overflow user Thanks.)

Use ^T to swap the previous two letters

This works in all Cocoa apps, but I like it especially when coding. Use ^T (Control-T) to swap the two letters adjacent to the caret, or when the caret is at the end, the two letters before the caret. For example:

fi^T

... becomes:

if

... which is a common typo I make.

Right click on any word and select 'Find Selected Text in API Reference' to search the API for that word. This is very helpful if you need to look up the available properties and/or methods for a class. Instead of heading to Apple.com or Google you will get a popup window of what you were looking for (or what was found).

In PyObjC, you can do the equivalent of #pragma mark for the symbols dropdown:

#MARK: Foo

and

#MARK: -

⌘` to properly format (reindent) your code

EDIT: Apparently re-indent feature (Edit > Format > Reindent) has no default shortcut. I guess I assigned one (in Preferences > Key bindings) a long time ago and don't even remember about that. Sorry for misleading you.

  1. Hold down option while selecting text to select non-contiguous sections of text.
  2. Hold down option while clicking on the symbol name drop down to sort by name rather than the order they appear in the file.

Being able to split the current editor window horizontally, which is great for wide screen monitors to be able to view the source and header file side by side. There are two different methods for doing depending on what version of Xcode you are using.

In Xcode 3.0 it is under Preferences, Key Bindings, Text Key Bindings at the bottom of that list.

In Xcode 2.5 it is under Preferences, Key Bindings, Menu Key Bindings, View menu.

A. It will build and analyze, meaning that Xcode will warn you about possible leaks.

Highlight Blocks of Code (Focus Follows Selection)

Activate "Focus Follow Selection" from View -> Code Folding -> Focus Follows Selection or ControlOptionf.

This also works for Python code, but leading whitespace in a line will throw it off. To fix it, install Google's Xcode Plugin and activate "Correct Whitespace on Save" in the preference thing that it installs. This will clear trailing whitespace every time you save a file, so if the highlighting get's screwed up, you can just save the file and it will work again. (And see, this is actually two hints in one, because this feature from the plugin is useful to have on its own).

Here is an example with some random Python code I just wrote. I am using the Midnight Xcode syntax coloring theme.

Some random Python code.

This is really helpful for highly nested parts of the code, to keep track of what is where. Also, notice how on the left, just to the right of the line numbers, those parts are colored too. That is the code folding bar. If you run your mouse down the side, it highlights the part under the mouse. And any of those colored bars can be folded, in other words, the parts of the code that are highlighted are exactly those parts that can be folded.

I just discovered how to change the indentation behavior used in the text macros:

For example, if you are like me and don't like this:

if (cond) {
  code;
}

but prefer this instead:

if (cond)
{
  code;
}

then you can change this globally (for all languages) by setting the following defaults in the terminal:

defaults write com.apple.Xcode XCCodeSenseFormattingOptions -dict-add BlockSeparator "\n"

This has been bugging me for years, I hope it is of some interest for someone else as well.

The documentation for this feature can be found in the Xcode User Default Reference

enter image description here

  1. To Open the debugging window on Debugger starts Change the Debugging preferences shown in the image..

  2. To clear the console log everytime app runs, check the Auto clear Debug Console.

When you use code completion on a method and it has multiple arguments, using CTRL + / to move to the next argument you need to fill in.

The User Scripts menu has a lot of goodies in it, and it's relatively easy to add your own. For example, I added a shortcut and bound it to cmd-opt-- to insert a comment divider and a #pragma mark in my code to quickly break up a file.

  #!/bin/sh
  echo -n "//================....================
  #pragma mark "

When I hit cmd-opt--, these lines are inserted into my code and the cursor is pre-positioned to edit the pragma mark component, which shows up in the symbol popup.

If you have a multi-touch capable Mac - use MultiClutch to map some of the keystrokes described by mouse gestures.

I use three finger forward and back to go forward and back in file history (cmd-alt-.), and pinch to switch between .h and .m.

Use AppKiDo to browse the documentation.

Use Accessorizer for a bunch of mundane, repetitive tasks in Xcode.

To link a new framework

(In the Groups and Files pane, open the Targets disclosure triangle to display the targets associated with your project.)

  1. In the Groups and Files pane, double-click your current project target to display the Target Info panel.
  2. In the Info panel, select the General tab. The lower pane displays the currently-linked frameworks.
  3. Add a new framework by pressing the + button at the bottom left of the panel and selecting from the list presented in the sheet that appears. (Importantly, the list in the sheet shows only the frameworks relevant to the target...)

(This wasn't available two years ago, but it's nevertheless worth pointing out as a significant time-saver over finding the framework in the filesystem and dragging it into the project...)

Move back or forward a full word with alt-. Move back or forward a file in your history with cmd-alt-. Switch between interface and implementation with cmd-alt-.

Jump to the next error in the list of build errors with cmd-=. Display the multiple Find panel with cmd-shift-f. Toggle full editor visibility with cmd-shift-e.

Jump to the Project tab with cmd-0, to the build tab with cmd-shift-b and to the debug tab with cmd-shift-y (same as the key commands for the action, with shift added).

Cmd + ~ (tilde - looks weird on the button...)

To switch between any open Xcode window - also when multiple projects are open.

  • To "set next statement", just drag the red instruction pointer to the next line to execute. (source)

Alt-Left & Right to go to the end/start of the line. This along with the CTRL-Left & Right to move to the next capital letter, or word break. these two save me so much time

I have no idea if everybody knows this already, but I was delighted when I learned I could use "code folding" and hide nested functions that I didn't want to look at by clicking on the gray area nearest to the code that you want to fold.

Hard to explain . . .

  1. Cmd+Option+O to open a file in a separate window.
  2. Can configure Tab to always indent. I frequently use it to indent an entire file.
  3. Ctrl+Arrow keys to move between camel case words. If you have OneTwo, you can move from One to Two with Ctrl+Right arrow.
  4. You can use emacs bindings, there's even kill ring! I use the Ctrl+w and Cmd+C together when I need to copy two different pieces of text.
  5. In the documentation browser, you can restrict your searches to a particular library, e.g., just iOS 4.2 library. This helps me focus on API available only on a particular iOS/Mac version of the SDK.
  6. Cmd+Shift+A to build and analyze.

I came into Xcode right from Windows world (as MANY others), and one of the first quirks which I was faced to, was trying to "indent a selected block of text" with the TAB key.

Typically, when using a Windows editor, you select a block of text, and whenever you press TAB (or shift TAB) keys, the selected text jumps right/left. Then, once you decide the new position of the text, you stop pressing TAB.

OK, in Xcode, this is completely different, because when you press TAB, the whole block of text disappears, leaving you with a silly face, and some anger inside...

But then, just by chance or intuition or something, one day I discovered some kind of workaround to achieve the same effect you might get under a proper windows editor. The steps should be these:

  1. Select the text block as you might do under Windows.
  2. Instead of pressing TAB, leave your instincts away, and "copy the text block" (typically CTRL+C (yuck)).
  3. Then, without deselecting the text, (pressing SHIFT if needed), extend the beginning of the selection and place it on the position you would like your new text to appear.
  4. Paste the beforementioned text (typically CTRL+V (yuck again)).
  5. Result: The previous text block gets substituted by "the new" one (of course, itself), but the "auto indent" capabilities of Xcode (or someone else, who cares), will auto place the text starting onto the new position we chose in step 3.
  6. A big smile appears on your face.

It's kind of tricky, but when you get used to it, you find yourself using it a lot.

Enjoy!!

Related