Creating Custom Xcode 4 File Templates

by Bob McCune on March 4, 2012

When Xcode 4 was released about a year ago it introduced an entirely new Project and File Template syntax. This was initially frustrating to me as the new syntax invalidated all of the custom templates I had written for Xcode 3. However, the new template format has proven to be more flexible and capable and represents an improvement over the old format. Now that Xcode 4.3 is officially available I thought it would be a good time to discuss creating custom file templates. In this post I’ll explain the file template layout, structure, and syntax and then finish up by creating some custom templates to simplify building Singleton objects and generating GHUnit test cases.

Getting Started

The easiest way to become familiar with Xcode’s template format is to study the default templates included with Xcode itself. Unfortunately, Apple doesn’t document the syntax, but a lot can be learned simply by experimenting with the ones already included with Xcode. The repackaging of Xcode 4.3 into a single app bundle makes it a little less obvious where to find these files. They still exist on disk, but instead of finding them under the /Developer folder you’ll find them inside of the Xcode.app bundle itself:

Mac Templates

iOS Templates

Open them up and take a look at their content and structure, but I would strongly warn against editing these files. Making an invalid edit to the default templates can render them useless and cause Xcode to crash. Instead, copy any of them you would like to modify into your “user templates” directory. This directory isn’t automatically created so you’ll need to create the following directory if it doesn’t already exist:

Any templates that you modify or create from scratch should be organized into their own specific directory. It’s best to give the directory a meaningful name, such as your company name, so they show up neatly in Xcode. For the remainder of this article it is assumed all file templates I’m creating will exist in a directory called TapHarmonic.

Let’s start to discuss the syntax by breaking down the components of a template.

The Template Container

A template is a collection of files contained within a directory with an .xctemplate extension. This is just an ordinary folder, but the .xctemplate suffix is required for these directories to be recognized as templates by Xcode.

If you examine the contents of the various default templates you’ll typically find the following items:

File Role
TemplateInfo.plist TemplateInfo.plist defines the template configuration
TemplateIcon.icns A 128 X 128 icon displayed in Xcode’s New File dialog
___FILEBASENAME___.h The template header file to be created
___FILEBASENAME___.m The template implementation file to be created

Before examining the template components in more detail let’s begin by creating a new template directory. Create a new directory called Custom Template.xctemplate. You may want to copy the TemplateIcon.icns from one of the other template directories so it will have an icon in the New File dialog. We’ll begin creating our custom template by starting with its configuration file.

Understanding TemplateInfo.plist

The most important file in the template is TemplateInfo.plist. This is a standard Apple plist describing the behavior of the template. It allows you to define one or more output files to create, provides syntax for creating user input screens, and enables creating custom variables to be used when generating your code. You can edit the contents of this file in Xcode’s plist editor, but my recommendation is to use a standard text editor like TextMate or BBEdit.

There are two distinct sections to this file: the first defines the general template configuration and the second defines the template’s user interface and output variables. I’ll begin by starting with the general keys and values common to all templates:

Key Value(s)
AllowedTypes An array of strings specifying one or more valid source types
DefaultCompletionName Defines the name that will be presented in the save dialog
Description Defines the description string for this template. This value will be displayed in the New File dialog
Kind In all templates you create this value will be Xcode.IDEKit.TextSubstitutionFileTemplateKind
MainTemplateFile The main source or resource file this template will create
Platforms An array of strings containing the valid platforms for this template
Summary Summary info for the template
SortOrder The order in which this template will appear in the New File dialog
BuildableType This value can be used to prepopulate the target checkboxes on the “Save” dialog. Valid values include: None and Test

Armed with the keys and values above, we can begin constructing a simple template with a minimal TemplateInfo.plist.

This provides enough configuration for our simple template, but before any actual output can be created we need to add some source files.

Source Files

We want the output from this template to be an Objective-C class. The template’s MainTemplateFile value refers to a file named ___FILEBASENAME___.m. We’ll create this file in our template directory along with its associated header.

___FILEBASENAME___.h

___FILEBASENAME___.m

The source templates have a number of values prefixed and suffixed with triple underscores. These are built-in expansion macros that can be used to provide dynamic values in your output. The following table lists the known macros:

Macro Expands To
___FILENAME___ The file name including extension
___FILEBASENAMEASIDENTIFIER___ The file name without its extension converted to valid C-style identifier
___PROJECTNAME___ The project name
___PROJECTNAMEASIDENTIFIER___ The project name converted to valid C-style identifier
___USERNAME___ The short user account name. In my case, “Bob”
___FULLUSERNAME___ The full user name. In my case, “Bob McCune”
___ORGANIZATIONNAME___ The organization name defined in your Xcode project
___DATE___ Today’s date
___TIME___ The current time
___YEAR___ The current four-digit year

Now that we’ve created our template directory, added its icon, plist, and source files we’re ready to put it into action. Select File > New > File… and you should see the template displayed in the dialog.

This basic template will have no custom user interface. You’ll simply select the template, provide a file name when prompted, select the applicable targets, and press the “Create” button. This level of simplicity works fine for basic templates such as ones generating a protocol or class extension, but Xcode 4 provides some more advanced features to capture user input.

Building the User Interface

Xcode’s template syntax defines an optional “Options” structure used to configure the template’s user interface. The Options key defines an array of dictionary elements that describe the user input components, user interface strings, and custom output variables.

Key Value(s)
Default A default value to be used if not specified by the user
Description The input type description. This value will be displayed as a tooltip when you hover over the input component
Identifier Unique identifier defining the output variable from this component
Name The input component’s label name. This value is displayed to the left of the component or to the right if the type is checkbox
Required Boolean value indicating if this input is required for the template to complete
Type The component type to use for this input. Valid values are: static, text, combo, popup, class, and buildSetting
NotPersisted Boolean value indicating if the input value will be persisted for future use
FallbackHeader The “fallback” import value to be used if the location of the class you are subclassing can’t be determined. Only relevant when when the Type value is class
Suffixes A dictionary of suffixes to append based on the type you are subclassing. This can be used to assist in adopting common naming conventions based on the type being subclassed, e.g. XXXViewController
Values An array of values to provide if the type is combo, popup, or class
RequiredOptions Can be used to enable/disable secondary components based on selections of a multi-value input control

We’ve seen some examples of how to use the built-in expansion macros to merge dynamic data into our template, but how do we take the input from our user interface and map it into our template source? The Identifier defines the variable name we can use in our source template files to reference its associated value. For instance, if your template defines an Identifier called viewColor, you can reference the variable’s value in the source template using either ___VARIABLE_viewColor___ or ___VARIABLE_viewColor:identifier___. The latter form ensures the value is munged to a valid C identifier.

Source File Grouping

In the template we’ve been building so far our source template files reside at the same directory level as the TemplateInfo.plist. It’s important to understand if your input component is a popup, combo, or class, Xcode will look for subdirectories in your .xctemplate file mapping to the values provided by the input element. For instance, if you have a popup element defined in your configuration:

The template will expect to find your MainTemplateFile under a Red, Green, or Blue directory. If you don’t provide this directory structure the template will either silently fail or will result in an Xcode crash. The need to have several, often subtle, variants of your template source files does result in a fair amount of redundancy, but does provide a convenient way of grouping template contents. Take a look at Apple’s Objective-C class.xctemplate for some concrete examples of how this works.

Creating Custom Templates

You should now have a better understanding of the template syntax and how the default templates are built. We’ve used this knowledge to build a simple, but not particularly useful template. Let’s walk through a couple more practical examples.

Creating a Custom Singleton Template

It would be nice to build a file template that simplifies the creation of a new Singleton object. There are a number of different approaches you could take when developing a Singleton, but I’ll define this template in terms of two different Singleton styles: Traditional and Grand Central Dispatch (CGD)-style. For the record, that latter is what you should choose when developing for iOS 4 and above.

This template should prompt us for the name of the class we want to create and provide a pop up menu for us to select the Singleton style. Additionally, it would be helpful if it could remember our last used style option.

We’ll begin by creating a new directory called Singleton class.xctemplate. Since our user interface will contain a popup selector we’ll additionally need to create two subdirectories corresponding to the popup’s values. Both the GCD and Traditional subdirectories will contain a a ___FILEBASENAME___.h and ___FILEBASENAME___.m file.

I won’t describe all the source files, but will show the template file for the GCD-style implementation.

Running this template will provide us with the following user interface and output:

Creating a Custom GHUnit Test Case Template

Xcode includes some basic unit testing support built on OCUnit. Although its support for unit testing continues to improve I’ve never been a big fan of its built-in functionality. Instead, I greatly prefer using the open source framework called GHUnit. GHUnit better conforms to other XUnit testing frameworks and definitely provides a more comprehensive solution.

Creating a new GHUnit test case can be a little tedious. Without a file template the process usually goes something like this:

  1. Create an Objective-C class under my UnitTest target.
  2. Copy the @interface section from the header file and paste it into the implementation file and then delete the header file.
  3. Import the class I’m going to test.
  4. Stub out the the setUp and tearDown methods.
  5. Stub out a test method.

Whew! That’s a lot of work before you can even write a single line of test code! This level of impedance will almost certainly dissuade you from writing many unit tests. Luckily we can greatly simplify this process by creating a custom file template.

The source looks like:

Running this template will provide us with the following user interface and output the test case for a User class:

Conclusion

Hopefully this post provided a helpful explanation of the syntax to create custom File Templates in Xcode 4. Even if you don’t find the need to build custom templates from scratch I highly recommend modifying Apple’s default templates to better suit your needs. A little bit of automation can go a long way in improving your development processes and accelerating your development cycles.

Download: Custom File Templates