Episode #48

Code Snippets

10 minutes
Published on January 10, 2013

This video is only available to subscribers. Get access to this video and 572 others.

In this episode we examine Xcode's code snippets feature and how it can speed up your day to day development. We also take a look at a handy gem for easily installing code snippets you've found online.

Episode Links

Creating your own snippets

You can copy any code you have in your project and drag it over to the snippets library. If you want to add the replacement tokens, you can add blocks like this: <# replace me #>.

Anatomy of the .codesnippet plist format

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE plist PUBLIC &quot;-//Apple Computer//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;
&lt;plist version=&quot;1.0&quot;&gt;
&lt;dict&gt;
    &lt;key&gt;IDECodeSnippetCompletionPrefix&lt;/key&gt;
    &lt;string&gt;continuation&lt;/string&gt;
    &lt;key&gt;IDECodeSnippetCompletionScopes&lt;/key&gt;
    &lt;array&gt;
        &lt;string&gt;TopLevel&lt;/string&gt;
    &lt;/array&gt;
    &lt;key&gt;IDECodeSnippetContents&lt;/key&gt;
    &lt;string&gt;
        @interface &amp;lt;#Class Name#&amp;gt; ()
        &amp;lt;#Continuation#&amp;gt;
        @end&lt;/string&gt;
    &lt;key&gt;IDECodeSnippetIdentifier&lt;/key&gt;
    &lt;string&gt;04BE9D9D-1F1B-4BD5-82FB-EC29B8C118A3&lt;/string&gt;
    &lt;key&gt;IDECodeSnippetLanguage&lt;/key&gt;
    &lt;string&gt;Xcode.SourceCodeLanguage.Objective-C&lt;/string&gt;
    &lt;key&gt;IDECodeSnippetTitle&lt;/key&gt;
    &lt;string&gt;Class Continuation&lt;/string&gt;
    &lt;key&gt;IDECodeSnippetUserSnippet&lt;/key&gt;
    &lt;true/&gt;
    &lt;key&gt;IDECodeSnippetVersion&lt;/key&gt;
    &lt;integer&gt;2&lt;/integer&gt;
&lt;/dict&gt;
&lt;/plist&gt;

Installing 3rd party snippets

Once you've found some snippets you want to try out, using the Xcode Snippets gem is very useful. It allows you to maintain a human readable list of snippet files, but also rename them to the UUID version that Xcode needs.

To start, you should migrate any existing snippets you've created by hand:

xcodesnippets migrate

Then you can install individual snippets like this:

xcodesnippets install some-cool-thing.codesnippet

The code snippets Xcode uses can be found in ~/Library/Developer/Xcode/UserData/CodeSnippets. The files that the xcodesnippets gem manages can be found in ~/Library/Developer/Xcode/UserData/ManagedCodeSnippets.

If you are making tweaks to a snippet, keep in mind that you'll probably have to delete it before re-importing it with the gem.