Using Snippets in Xcode

If you have done any editing of Objective-C source code in Xcode, you have probably noticed that it will sometimes give you useful templates of code to save typing. For example, if you type “switch” into the Xcode editor window inside a method body and press return, you get something like this:

Typing on the keyboard overwrites the “expression” placeholder and tabbing moves to the “constant” placeholder and so on. It’s called a snippet and is a useful feature, marred only by it not being very intelligent when it comes to matching indentation to the context in which it is used.

There are lots of built-in snippet declarations in Xcode. For Objective-C they cover conditional statements, class declarations, categories, protocols and so on. It’s simple to review the snippets that are defined using the snippet library in Xcode: Assuming you have the Utilities pane displayed, you access this using the “{}” tab and it looks something like this:

Clicking on a snippet displays a popover showing the content of the snippet and there is an edit button that allows you to adjust it to your own taste:

What’s nice about the snippet library is that it’s really easy to define your own custom snippets for constructs that you use a lot. As an example, something I like to define is a pre-formatted action sheet invocation. The basic structure doesn’t change but the button labels do, and placeholders can be created for these using special tags in the snippet of the form <#label#>.

To create a new snippet, find an existing action sheet invocation (or whatever else you need), select the code with the mouse and drag the selection to the snippet library. Then edit the new snippet, giving it a title, description and completion shortcut. Use the special tag syntax to create placeholders for whatever you want to be configurable during editing:

Now, whenever you type the completion shortcut into Xcode’s editor window, subject to the completion scope (method, top-level, etc.), the template will be inserted when you press return. You can then type to overwrite the placeholders and move between placeholders using the tab key. Tidy up the formatting and away you go!

You can learn more about defining action sheets and other similar user-interface components on Learning Tree’s iPhone® and iPad® Programming: A Comprehensive Hands-On Introduction course. To learn more about Objective-C, check out Hands-On Objective-C Programming.

Richard Senior

Type to search

Do you mean "" ?

Sorry, no results were found for your query.

Please check your spelling and try your search again.