Be More Productive in Xcode Using Code Snippets
- Built-In Code Snippets
- User-Defined Code Snippets
- Completion Shortcuts / Adding Placeholders / Sharing Code Snippets
One of the most underrated features of Xcode 4 is code snippets. A code snippet is a small block of code that you add to the source code for your project. Using Xcode code snippets saves you time by eliminating the need to type commonly used, and repeated, pieces of code.
I use code snippets to do everything from adding file header comments to defining properties to creating stub methods that respond to UITableViewDataSource and UITableViewDelegate protocol messages. Any piece of source code or comment that you can type into a file can be used as a code snippet in Xcode.
Code snippets are easy to use, but surprisingly, many Xcode developers don't even know they exist. Let's take some time to explore Xcode code snippets, so you can take advantage of them and impress others on your team with your Xcode Fu.
Built-In Code Snippets
Xcode comes with a list of pre-defined code snippets. These code snippets are found in the Code Snippet Library, which is found at the bottom of the Utilities area (see Figure 1). Or you can type Command-Control-Option-2 to quickly show the library.
The pre-defined code snippets cover a slew of common coding tasks, from performing a Core Data fetch to observing a keypath value to defining blocks of C code such as if, while, and switch statements.
There are three ways to use a code snippet:
- Drag a code snippet from the library into the editor containing your source code (see Figure 2).
- Highlight a portion of the code snippet and drag it from the code snippet information popup window into the file displayed in the editor (see Figure 3).
- Type the completion shortcut in your source file. You can see the code snippet in the code completion popup window as you type the completion shortcut (see Figure 4). This is the fastest way to add a code snippet to your code.