Xcode Snippets

July 25, 2012

Xcode’s snippets feature is rather handy. It’s what drives many of the autocomplete templates. For instance, if you type init on a new line and hit return, Xcode will create a template for an -init method.

Until recently I haven’t bothered to create my own snippets, which can be done in three easy steps:

  • Selecting a block of text you wish to make a snippet.
  • Drag it onto the Code Snippet Library, which is part of the Utility Area (lower right hand side).
  • Customize by entering the Completion Shortcut, or wrapping tokens in <#token#> so that you can tab between them after the snippet has been inserted.

I do a fair amount of Quartz development, so today I created a a snippet which has already proven useful. I’ve set its completion shortcut to cgbitmapcontextcreate:

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef ctx = CGBitmapContextCreate(<#data#>, <#width#>, <#height#>,
	                                     8, <#width#> * 4, colorSpace, 
	                                     kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);

I’ve made a separate one just for color spaces, cgcolorspace, as for some reason the repetitiveness of creating and releasing RGB CGColorSpaceRefs has lost its luster.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
<#code#>
CGColorSpaceRelease(colorSpace);

Thankfully you can stomp all over the symbol names that will be otherwise provided by autocomplete, so when I’m about to create yet another CGColorSpaceRef, perhaps forgetting my snippet, Xcode will show me the snippet as the first autocomplete option in addition to the usual bunch.

A pleasant side effect of this is that you can fix some of Xcode’s annoying autocompletes, due to how snippets take priority over other autocomplete suggestions. For instance, when I type NSStri in Xcode, the default autocompletion is NSStrikethroughStyleAttributeName. Probably not what I wanted. I can use snippets to fix this by creating an NSString snippet with the very same completion shortcut, and voila, autocomplete gives me just what I want when I next start typing NSString.

Tags: ,