<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Bob McCune</title>
	<atom:link href="http://www.bobmccune.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bobmccune.com</link>
	<description>iOS Design, Development, Training, and Mentoring</description>
	<lastBuildDate>Mon, 26 Mar 2012 02:01:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
	<atom:link rel='hub' href='http://www.bobmccune.com/?pushpress=hub'/>
		<item>
		<title>iOS 5 Face Detection with Core Image</title>
		<link>http://www.bobmccune.com/2012/03/22/ios-5-face-detection-with-core-image/</link>
		<comments>http://www.bobmccune.com/2012/03/22/ios-5-face-detection-with-core-image/#comments</comments>
		<pubDate>Thu, 22 Mar 2012 16:00:25 +0000</pubDate>
		<dc:creator>Bob McCune</dc:creator>
				<category><![CDATA[iOS]]></category>
		<category><![CDATA[Quartz]]></category>

		<guid isPermaLink="false">http://www.bobmccune.com/?p=504</guid>
		<description><![CDATA[One of the great new features of iOS 5 is the addition of the Core Image (CI) framework. This framework has been available for a few years on the Mac, but now its advanced image processing and filtering capabilities are available on the iOS platform as well. One particularly cool new feature available in Core [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>One of the great new features of iOS 5 is the addition of the Core Image (CI) framework.  This framework has been available for a few years on the Mac, but now its advanced image processing and filtering capabilities are available on the iOS platform as well.  One particularly cool new feature available in Core Image, on both iOS 5 and Lion, is its ability to detect faces in an image.  Thanks to some recent inspiration from <a href="https://twitter.com/#!/jonsteinmetz" title="Jon Steinmetz">Jon Steinmetz</a> over at <a href="http://pixelresearchlabs.com/" title="Pixel Research Labs">Pixel Research Labs</a> I have put together this tutorial showing how to use this great new feature.</p>
<h2 id="getting_started">Getting Started</h2>
<p>The face detection API is <em>surprisingly</em> simple to use.  It really boils down to two classes: <code>CIDetector</code> and <code>CIFaceFeature</code>.  <code>CIDetector</code> is responsible for performing the analysis of an image and returns a collection of <code>CIFaceFeature</code> objects describing the face(s) found in the image.  You begin by creating a new instance of <code>CIDetector</code> using its <code>detectorOfType:context:options</code> class method.  </p>
<pre>CIDetector *detector =
    [CIDetector detectorOfType:CIDetectorTypeFace context:nil options:options];
</pre>
<p><code>CIDetector</code> can currently only be configured to perform face detection so you&#8217;ll always pass the string constant <code>CIDetectorTypeFace</code> for the type argument.  The context and options arguments are optional, but you will typically provide it an options dictionary describing the accuracy level to use.  This can be configured by defining a dictionary with the key <code>CIDetectorAccuracy</code> and a value of either <code>CIDetectorAccuracyLow</code> or <code>CIDetectorAccuracyHigh</code>.  The high accuracy algorithm can produce far more accurate results, but takes significantly longer to perform the analysis.  Depending on what you need to accomplish you may find the low accuracy setting produces acceptable results.</p>
<h2 id="analyzing_the_image">Analyzing the Image</h2>
<p>With a properly configured detector in hand you&#8217;re ready to analyze an image.  You call the detector&#8217;s <code>featuresInImage:</code> method passing it an image to analyze.  The Core Image framework doesn&#8217;t know anything about <code>UIImage</code> so you can&#8217;t directly pass it an image of this type, however, UIKit provides a category on <code>CIImage</code> making it easy to create an instance of <code>CIImage</code> from a <code>UIImage</code>.</p>
<pre>UIImage *uiImage = [UIImage imageNamed:@"image_name"];
CIImage *ciImage = [[CIImage alloc] initWithImage:uiImage];
NSArray *features = [detector featuresInImage:ciImage];
</pre>
<p>The <code>featuresInImage:</code> method will return a collection of <code>CIFaceFeature</code> objects describing the features of the detected faces. Specifically, each instance defines a face rectangle, and points for the left eye, right eye, and mouth.  It only defines the center point of each feature so you&#8217;d have to perform some additional calculations if you&#8217;d need to know the feature&#8217;s shape, angle, or relative location.</p>
<h2 id="visualizing_the_results">Visualizing the Results</h2>
<p>The following images show examples of the face detection API in action.  The images illustrate the differences between the low and high accuracy settings along with the approximate times it took to run the detection.  The location of the detected features is not significantly different between the two images, but you&#8217;ll notice the high accuracy setting took more that 10x longer to compute on an iPhone 4.  It will likely require a fair amount of testing of a representative set of images to determine the appropriate accuracy setting for your app.</p>
<table>
<tr>
<td>
			<img src="http://www.bobmccune.com/wp-content/uploads/2012/03/slow.png" title="slow" width="280" height="306">
		</td>
<td>
			<img src="http://www.bobmccune.com/wp-content/uploads/2012/03/fast.png" title="slow" width="280" height="306">
		</td>
</tr>
<tr>
<td style="text-align: center;">
			<code>CIDetectorAccuracyLow</code><br/>
<p class="format_text">~253ms on iPhone 4</p>
</td>
<td style="text-align: center;">
			<code>CIDetectorAccuracyHigh</code><br/>
<p class="format_text">~ 2810ms on iPhone 4</p>
</td>
</tr>
</table>
<p>I have put together a sample app containing images of several iconic faces.  Flip through the images and run the analysis to see the face detection in action.  You can run the sample on the simulator, but I&#8217;d recommend running it on your device so you can get a realistic sense for the performance.  Enjoy!</p>
<p style="margin-bottom: 15px;">
Download iOS 5 Sample App: <a href='http://www.bobmccune.com/wp-content/uploads/2012/03/FaceDetection.zip'>Faces</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.bobmccune.com/2012/03/22/ios-5-face-detection-with-core-image/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating Custom Xcode 4 File Templates</title>
		<link>http://www.bobmccune.com/2012/03/04/creating-custom-xcode-4-file-templates/</link>
		<comments>http://www.bobmccune.com/2012/03/04/creating-custom-xcode-4-file-templates/#comments</comments>
		<pubDate>Sun, 04 Mar 2012 14:00:08 +0000</pubDate>
		<dc:creator>Bob McCune</dc:creator>
				<category><![CDATA[iOS]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://www.bobmccune.com/?p=485</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>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 <a href="http://itunes.apple.com/us/app/xcode/id497799835?mt=12" title="XCode on Mac App Store">Xcode 4.3</a> is officially available I thought it would be a good time to discuss creating custom file templates.  In this post I&#8217;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.</p>
<h2 id="gettingstarted">Getting Started</h2>
<p>The easiest way to become familiar with Xcode&#8217;s template format is to study the default templates included with Xcode itself.  Unfortunately, Apple doesn&#8217;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 <code>/Developer</code> folder you&#8217;ll find them inside of the Xcode.app bundle itself:</p>
<p><span id="more-485"></span></p>
<h3 id="mactemplates">Mac Templates</h3>
<pre>/Applications/Xcode.app/Contents/Developer/Library/Xcode/Templates/File Templates</pre>
<h3 id="iostemplates">iOS Templates</h3>
<pre>/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/File Templates</pre>
<p>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 &#8220;user templates&#8221; directory.  This directory isn&#8217;t automatically created so you&#8217;ll need to create the following directory if it doesn&#8217;t already exist:</p>
<pre>~/Library/Developer/Xcode/Templates/File Templates/</pre>
<p>Any templates that you modify or create from scratch should be organized into their own specific directory.  It&#8217;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&#8217;m creating will exist in a directory called <code>TapHarmonic</code>.</p>
<div><img src="http://www.bobmccune.com/wp-content/uploads/2012/03/filesystem.png" alt="" title="filesystem" width="397" height="217" class="alignnone size-full wp-image-488" /></div>
<p>Let&#8217;s start to discuss the syntax by breaking down the components of a template.</p>
<h3 id="thetemplatecontainer">The Template Container</h3>
<p>A template is a collection of files contained within a directory with an <code>.xctemplate</code> extension.  This is just an ordinary folder, but the <code>.xctemplate</code> suffix is required for these directories to be recognized as templates by Xcode.</p>
<p>If you examine the contents of the various default templates you&#8217;ll typically find the following items:</p>
<table class="gridtable">
<tr>
<th>File</th>
<th>Role</th>
</tr>
<tr>
<td><code>TemplateInfo.plist</code></td>
<td><code>TemplateInfo.plist</code> defines the template configuration</td>
</tr>
<tr>
<td><code>TemplateIcon.icns</code></td>
<td>A 128 X 128 icon displayed in Xcode&#8217;s New File dialog</td>
</tr>
<tr>
<td><code>___FILEBASENAME___.h</code></td>
<td>The template header file to be created</td>
</tr>
<tr>
<td><code>___FILEBASENAME___.m</code></td>
<td>The template implementation file to be created</td>
</tr>
</table>
<p>Before examining the template components in more detail let&#8217;s begin by creating a new template directory.  Create a new directory called <code>Custom Template.xctemplate</code>.  You may want to copy the <code>TemplateIcon.icns</code> from one of the other template directories so it will have an icon in the New File dialog.  We&#8217;ll begin creating our custom template by starting with its configuration file.</p>
<h3 id="understandingtemplateinfo.plist">Understanding TemplateInfo.plist</h3>
<p>The most important file in the template is <code>TemplateInfo.plist</code>.  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&#8217;s plist editor, but my recommendation is to use a standard text editor like <a href="http://macromates.com/" title="TextMate">TextMate</a> or <a href="http://www.barebones.com/" title="BBEdit">BBEdit</a>.</p>
<p>There are two distinct sections to this file: the first defines the general template configuration and the second defines the template&#8217;s user interface and output variables.  I&#8217;ll begin by starting with the general keys and values common to all templates:</p>
<table class="gridtable">
<tr>
<th>Key</th>
<th>Value(s)</th>
</tr>
<tr>
<td><code>AllowedTypes</code></td>
<td>An array of strings specifying one or more valid source types</td>
</tr>
<tr>
<td><code>DefaultCompletionName</code></td>
<td>Defines the name that will be presented in the save dialog</td>
</tr>
<tr>
<td><code>Description</code></td>
<td>Defines the description string for this template.  This value will be displayed in the New File dialog</td>
</tr>
<tr>
<td><code>Kind</code></td>
<td>In all templates you create this value will be <code>Xcode.IDEKit.TextSubstitutionFileTemplateKind</code></td>
</tr>
<tr>
<td><code>MainTemplateFile</code></td>
<td>The main source or resource file this template will create</td>
</tr>
<tr>
<td><code>Platforms</code></td>
<td>An array of strings containing the valid platforms for this template</td>
</tr>
<tr>
<td><code>Summary</code></td>
<td>Summary info for the template</td>
</tr>
<tr>
<td><code>SortOrder</code></td>
<td>The order in which this template will appear in the New File dialog</td>
</tr>
<tr>
<td><code>BuildableType</code></td>
<td>This value can be used to prepopulate the target checkboxes on the &#8220;Save&#8221; dialog.  Valid values include: <code>None</code> and <code>Test</code></td>
</tr>
</table>
<p>Armed with the keys and values above, we can begin constructing a simple template with a minimal <code>TemplateInfo.plist</code>.</p>
<pre>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
    &lt;key&gt;AllowedTypes&lt;/key&gt;
    &lt;array&gt;
        &lt;string&gt;public.objective-c-source&lt;/string&gt;
    &lt;/array&gt;
    &lt;key&gt;Description&lt;/key&gt;
    &lt;string&gt;A simple template to produce an Objective-C class.&lt;/string&gt;
    &lt;key&gt;Kind&lt;/key&gt;
    &lt;string&gt;Xcode.IDEKit.TextSubstitutionFileTemplateKind&lt;/string&gt;
    &lt;key&gt;MainTemplateFile&lt;/key&gt;
    &lt;string&gt;___FILEBASENAME___.m&lt;/string&gt;
    &lt;key&gt;Platforms&lt;/key&gt;
    &lt;array&gt;
        &lt;string&gt;com.apple.platform.iphoneos&lt;/string&gt;
    &lt;/array&gt;
&lt;/dict&gt;
&lt;/plist&gt;
</pre>
<p>This provides enough configuration for our simple template, but before any actual output can be created we need to add some source files.</p>
<h3 id="sourcefiles">Source Files</h3>
<p>We want the output from this template to be an Objective-C class.  The template&#8217;s <code>MainTemplateFile</code> value refers to a file named <code>___FILEBASENAME___.m</code>.  We&#8217;ll create this file in our template directory along with its associated header.</p>
<div><code>___FILEBASENAME___.h</code></div>
<pre>//
//  ___FILENAME___
//  ___PROJECTNAME___
//
//  Created by ___FULLUSERNAME___ on ___DATE___.
//  Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//

@interface ___FILEBASENAMEASIDENTIFIER___ : NSObject

@end
</pre>
<div><code>___FILEBASENAME___.m</code></div>
<pre>//
//  ___FILENAME___
//  ___PROJECTNAME___
//
//  Created by ___FULLUSERNAME___ on ___DATE___.
//  Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//

#import "___FILEBASENAME___.h"

@implementation ___FILEBASENAMEASIDENTIFIER___

@end
</pre>
<p>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:</p>
<table class="gridtable">
<thead>
<tr>
<th>Macro</th>
<th>Expands To</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>___FILENAME___</td>
<td>The file name including extension</td>
</tr>
<tr>
<td><code>___FILEBASENAMEASIDENTIFIER___</code></td>
<td>The file name without its extension converted to valid C-style identifier</td>
</tr>
<tr>
<td><code>___PROJECTNAME___</code></td>
<td>The project name</td>
</tr>
<tr>
<td><code>___PROJECTNAMEASIDENTIFIER___</code></td>
<td>The project name converted to valid C-style identifier</td>
</tr>
<tr>
<td><code>___USERNAME___</code></td>
<td>The short user account name.  In my case, &#8220;Bob&#8221;</td>
</tr>
<tr>
<td><code>___FULLUSERNAME___</code></td>
<td>The full user name.  In my case, &#8220;Bob McCune&#8221;</td>
</tr>
<tr>
<td><code>___ORGANIZATIONNAME___</code></td>
<td>The organization name defined in your Xcode project</td>
</tr>
<tr>
<td><code>___DATE___</code></td>
<td>Today&#8217;s date</td>
</tr>
<tr>
<td><code>___TIME___</code></td>
<td>The current time</td>
</tr>
<tr>
<td><code>___YEAR___</code></td>
<td>The current four-digit year</td>
</tr>
</tbody>
</table>
<p>Now that we&#8217;ve created our template directory, added its icon, plist, and source files we&#8217;re ready to put it into action.  Select File > New > File&#8230; and you should see the template displayed in the dialog.</p>
<div><img src="http://www.bobmccune.com/wp-content/uploads/2012/03/custom_template.png" alt="" title="custom_template" width="590" height="402" class="alignnone size-full wp-image-487" /></div>
<p>This basic template will have no custom user interface.  You&#8217;ll simply select the template, provide a file name when prompted, select the applicable targets, and press the &#8220;Create&#8221; 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.</p>
<h3 id="buildingtheuserinterface">Building the User Interface</h3>
<p>Xcode&#8217;s template syntax defines an optional &#8220;Options&#8221; structure used to configure the template&#8217;s user interface.  The <code>Options</code> key defines an array of dictionary elements that describe the user input components, user interface strings, and custom output variables.</p>
<table class="gridtable">
<thead>
<tr>
<th>Key</th>
<th>Value(s)</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Default</code></td>
<td>A default value to be used if not specified by the user</td>
</tr>
<tr>
<td><code>Description</code></td>
<td>The input type description.  This value will be displayed as a tooltip when you hover over the input component</td>
</tr>
<tr>
<td><code>Identifier</code></td>
<td>Unique identifier defining the output variable from this component</td>
</tr>
<tr>
<td><code>Name</code></td>
<td>The input component&#8217;s label name.  This value is displayed to the left of the component or to the right if the type is <code>checkbox</code></td>
</tr>
<tr>
<td><code>Required</code></td>
<td>Boolean value indicating if this input is required for the template to complete</td>
</tr>
<tr>
<td><code>Type</code></td>
<td>The component type to use for this input.  Valid values are: <code>static</code>, <code>text</code>, <code>combo</code>, <code>popup</code>, <code>class</code>, and <code>buildSetting</code></td>
</tr>
<tr>
<td><code>NotPersisted</code></td>
<td>Boolean value indicating if the input value will be persisted for future use</td>
</tr>
<tr>
<td><code>FallbackHeader</code></td>
<td>The &#8220;fallback&#8221; import value to be used if the location of the class you are subclassing can&#8217;t be determined.  Only relevant when when the <code>Type</code> value is <code>class</code></td>
</tr>
<tr>
<td><code>Suffixes</code></td>
<td>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</td>
</tr>
<tr>
<td><code>Values</code></td>
<td>An array of values to provide if the type is <code>combo</code>, <code>popup</code>, or <code>class</code></td>
</tr>
<tr>
<td><code>RequiredOptions</code></td>
<td>Can be used to enable/disable secondary components based on selections of a multi-value input control</td>
</tr>
</tbody>
</table>
<p>We&#8217;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 <code>Identifier</code> defines the variable name we can use in our source template files to reference its associated value.  For instance, if your template defines an <code>Identifier</code> called <code>viewColor</code>, you can reference the variable&#8217;s value in the source template using either <code>___VARIABLE_viewColor___</code> or <code>___VARIABLE_viewColor:identifier___</code>.  The latter form ensures the value is munged to a valid C identifier.</p>
<h3 id="sourcefilegrouping">Source File Grouping</h3>
<p>In the template we&#8217;ve been building so far our source template files reside at the same directory level as the <code>TemplateInfo.plist</code>.  It&#8217;s important to understand if your input component is a <code>popup</code>, <code>combo</code>, or <code>class</code>, Xcode will look for subdirectories in your <code>.xctemplate</code> file mapping to the values provided by the input element.  For instance, if you have a <code>popup</code> element defined in your configuration:</p>
<pre><code>&lt;key&gt;Options&lt;/key&gt;
&lt;array&gt;
    &lt;dict&gt;
        &lt;key&gt;Type&lt;/key&gt;
        &lt;string&gt;combo&lt;/string&gt;
        &lt;key&gt;Values&lt;/key&gt;
        &lt;array&gt;
            &lt;string&gt;Red&lt;/string&gt;
            &lt;string&gt;Green&lt;/string&gt;
            &lt;string&gt;Blue&lt;/string&gt;
        &lt;/array&gt;
    &lt;/dict&gt;
&lt;/array&gt;
</code></pre>
<p>The template will expect to find your <code>MainTemplateFile</code> under a <code>Red</code>, <code>Green</code>, or <code>Blue</code> directory.  If you don&#8217;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&#8217;s <code>Objective-C class.xctemplate</code> for some concrete examples of how this works.</p>
<h2 id="creatingcustomtemplates">Creating Custom Templates</h2>
<p>You should now have a better understanding of the template syntax and how the default templates are built.  We&#8217;ve used this knowledge to build a simple, but not particularly useful template.  Let&#8217;s walk through a couple more practical examples.</p>
<h3 id="creatingacustomsingletontemplate">Creating a Custom Singleton Template</h3>
<p>It would be nice to build a file template that simplifies the creation of a new <a href="http://en.wikipedia.org/wiki/Singleton_pattern" title="Singleton Pattern">Singleton</a> object.  There are a number of different approaches you could take when developing a Singleton, but I&#8217;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.</p>
<p>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.</p>
<p>We&#8217;ll begin by creating a new directory called <code>Singleton class.xctemplate</code>.  Since our user interface will contain a popup selector we&#8217;ll additionally need to create two subdirectories corresponding to the popup&#8217;s values.  Both the <code>GCD</code> and <code>Traditional</code> subdirectories will contain a  a <code>___FILEBASENAME___.h</code> and <code>___FILEBASENAME___.m</code> file.</p>
<pre>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
    &lt;key&gt;AllowedTypes&lt;/key&gt;
    &lt;array&gt;
        &lt;string&gt;public.objective-c-source&lt;/string&gt;
        &lt;string&gt;public.objective-c-plus-plus-source&lt;/string&gt;
    &lt;/array&gt;
    &lt;key&gt;Description&lt;/key&gt;
    &lt;string&gt;A Singleton class.&lt;/string&gt;
    &lt;key&gt;Kind&lt;/key&gt;
    &lt;string&gt;Xcode.IDEKit.TextSubstitutionFileTemplateKind&lt;/string&gt;
    &lt;key&gt;MainTemplateFile&lt;/key&gt;
    &lt;string&gt;___FILEBASENAME___.m&lt;/string&gt;
    &lt;key&gt;Options&lt;/key&gt;
    &lt;array&gt;
        &lt;dict&gt;
            &lt;key&gt;Description&lt;/key&gt;
            &lt;string&gt;The name of the Singleton class to create&lt;/string&gt;
            &lt;key&gt;Identifier&lt;/key&gt;
            &lt;string&gt;productName&lt;/string&gt;
            &lt;key&gt;Name&lt;/key&gt;
            &lt;string&gt;Class Name&lt;/string&gt;
            &lt;key&gt;NotPersisted&lt;/key&gt;
            &lt;true/&gt;
            &lt;key&gt;Required&lt;/key&gt;
            &lt;true/&gt;
            &lt;key&gt;Type&lt;/key&gt;
            &lt;string&gt;text&lt;/string&gt;
        &lt;/dict&gt;
        &lt;dict&gt;
            &lt;key&gt;Identifier&lt;/key&gt;
            &lt;string&gt;singletonStyle&lt;/string&gt;
            &lt;key&gt;Name&lt;/key&gt;
            &lt;string&gt;Singleton Style&lt;/string&gt;
            &lt;key&gt;Description&lt;/key&gt;
            &lt;string&gt;The style of Singleton to create.&lt;/string&gt;
            &lt;key&gt;Type&lt;/key&gt;
            &lt;string&gt;popup&lt;/string&gt;
            &lt;key&gt;Default&lt;/key&gt;
            &lt;string&gt;GCD&lt;/string&gt;
            &lt;key&gt;Values&lt;/key&gt;
            &lt;array&gt;
                &lt;string&gt;GCD&lt;/string&gt;
                &lt;string&gt;Traditional&lt;/string&gt;
            &lt;/array&gt;
        &lt;/dict&gt;
    &lt;/array&gt;
    &lt;key&gt;Platforms&lt;/key&gt;
    &lt;array&gt;
        &lt;string&gt;com.apple.platform.iphoneos&lt;/string&gt;
    &lt;/array&gt;
    &lt;key&gt;Summary&lt;/key&gt;
    &lt;string&gt;A Singleton class.&lt;/string&gt;
&lt;/dict&gt;
&lt;/plist&gt;
</pre>
<p>I won&#8217;t describe all the source files, but will show the template file for the GCD-style implementation.</p>
<pre>#import "___FILEBASENAME___.h"

@implementation ___FILEBASENAMEASIDENTIFIER___

+ (id)shared___FILEBASENAMEASIDENTIFIER___ {
    static dispatch_once_t predicate;
    static ___FILEBASENAMEASIDENTIFIER___ *instance = nil;
    dispatch_once(&amp;predicate, ^{instance = [[self alloc] init];});
    return instance;
}

@end
</pre>
<p>Running this template will provide us with the following user interface and output:</p>
<div><img src="http://www.bobmccune.com/wp-content/uploads/2012/03/singleton.png" alt="" title="singleton" width="590" height="402" class="alignnone size-full wp-image-489" /></div>
<pre>#import "UserManager.h"

@implementation UserManager

+ (id)sharedUserManager {
    static dispatch_once_t predicate;
    static UserManager *instance = nil;
    dispatch_once(&amp;predicate, ^{ instance = [[self alloc] init]; });
    return instance;
}

@end
</pre>
<h3 id="creatingacustomghunittestcasetemplate">Creating a Custom GHUnit Test Case Template</h3>
<p>Xcode includes some basic unit testing support built on OCUnit.  Although its support for unit testing continues to improve I&#8217;ve never been a big fan of its built-in functionality.  Instead, I greatly prefer using the open source framework called <a href="https://github.com/gabriel/gh-unit" title="GHUnit on GitHub">GHUnit</a>.  GHUnit better conforms to other <a href="http://en.wikipedia.org/wiki/XUnit" title="XUnit Testing">XUnit</a> testing frameworks and definitely provides a more comprehensive solution.</p>
<p>Creating a new GHUnit test case can be a little tedious.  Without a file template the process usually goes something like this:</p>
<ol>
<li>Create an Objective-C class under my <code>UnitTest</code> target.</li>
<li>Copy the <code>@interface</code> section from the header file and paste it into the implementation file and then delete the header file.</li>
<li>Import the class I&#8217;m going to test.</li>
<li>Stub out the the <code>setUp</code> and <code>tearDown</code> methods.</li>
<li>Stub out a test method.</li>
</ol>
<p>Whew!  That&#8217;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.</p>
<pre>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
    &lt;dict&gt;
        &lt;key&gt;AllowedTypes&lt;/key&gt;
        &lt;array&gt;
            &lt;string&gt;public.objective-c-source&lt;/string&gt;
        &lt;/array&gt;
        &lt;key&gt;DefaultCompletionName&lt;/key&gt;
        &lt;string&gt;Test&lt;/string&gt;
        &lt;key&gt;Description&lt;/key&gt;
        &lt;string&gt;A GHUnit Test Case&lt;/string&gt;
        &lt;key&gt;Kind&lt;/key&gt;
        &lt;string&gt;Xcode.IDEKit.TextSubstitutionFileTemplateKind&lt;/string&gt;
        &lt;key&gt;MainTemplateFile&lt;/key&gt;
        &lt;string&gt;___FILEBASENAME___.m&lt;/string&gt;
        &lt;key&gt;Platforms&lt;/key&gt;
        &lt;array&gt;
            &lt;string&gt;com.apple.platform.iphoneos&lt;/string&gt;
        &lt;/array&gt;
        &lt;key&gt;Options&lt;/key&gt;
        &lt;array&gt;
            &lt;dict&gt;
                &lt;key&gt;Default&lt;/key&gt;
                &lt;string/&gt;
                &lt;key&gt;Description&lt;/key&gt;
                &lt;string&gt;What would you like to test?&lt;/string&gt;
                &lt;key&gt;Identifier&lt;/key&gt;
                &lt;string&gt;cutClass&lt;/string&gt;
                &lt;key&gt;Name&lt;/key&gt;
                &lt;string&gt;Test case for&lt;/string&gt;
                &lt;key&gt;Required&lt;/key&gt;
                &lt;true/&gt;
                &lt;key&gt;NotPersisted&lt;/key&gt;
                &lt;true/&gt;
                &lt;key&gt;Type&lt;/key&gt;
                &lt;string&gt;text&lt;/string&gt;
            &lt;/dict&gt;
            &lt;dict&gt;
                &lt;key&gt;Default&lt;/key&gt;
                &lt;string&gt;___VARIABLE_cutClass:identifier___Test&lt;/string&gt;
                &lt;key&gt;Identifier&lt;/key&gt;
                &lt;string&gt;productName&lt;/string&gt;
                &lt;key&gt;Type&lt;/key&gt;
                &lt;string&gt;static&lt;/string&gt;
            &lt;/dict&gt;
        &lt;/array&gt;

        &lt;key&gt;Summary&lt;/key&gt;
        &lt;string&gt;A GHUnit Test Case&lt;/string&gt;
    &lt;/dict&gt;
&lt;/plist&gt;
</pre>
<p>The source looks like:</p>
<pre>#import "___VARIABLE_cutClass:identifier___.h"

@interface ___FILEBASENAMEASIDENTIFIER___ : GHTestCase
@end

@implementation ___FILEBASENAMEASIDENTIFIER___

- (void)setUp {

}

- (void)tearDown {

}

- (void)testMethod {
	// Implement test case
}

@end</pre>
<p>Running this template will provide us with the following user interface and output the test case for a <code>User</code> class:</p>
<div><img src="http://www.bobmccune.com/wp-content/uploads/2012/03/testcase.png" alt="" title="testcase" width="590" height="402" class="alignnone size-full wp-image-491" /></div>
<pre>#import "User.h"

@interface UserTest : GHTestCase
@end

@implementation UserTest

- (void)setUp {

}

- (void)tearDown {

}

- (void)testMethod {
    // Implement test case
}

@end
</pre>
<h2 id="conclusion">Conclusion</h2>
<p>Hopefully this post provided a helpful explanation of the syntax to create custom File Templates in Xcode 4.  Even if you don&#8217;t find the need to build custom templates from scratch I highly recommend modifying Apple&#8217;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.</p>
<p>Download: <a href='http://www.bobmccune.com/wp-content/uploads/2012/03/TapHarmonic.zip'>Custom File Templates</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.bobmccune.com/2012/03/04/creating-custom-xcode-4-file-templates/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>A funny thing happened on the way to the ARC</title>
		<link>http://www.bobmccune.com/2012/02/28/a-funny-thing-happened-on-the-way-to-the-arc/</link>
		<comments>http://www.bobmccune.com/2012/02/28/a-funny-thing-happened-on-the-way-to-the-arc/#comments</comments>
		<pubDate>Tue, 28 Feb 2012 18:37:42 +0000</pubDate>
		<dc:creator>Bob McCune</dc:creator>
				<category><![CDATA[iOS]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Quartz]]></category>

		<guid isPermaLink="false">http://www.bobmccune.com/?p=475</guid>
		<description><![CDATA[As I was preparing to post the QuartzDemos project on GitHub I decided to modernize the project and covert it to use Automatic Reference Counting (ARC). Overall this was fairly easy to do despite some of the slightly confusing rules related to bridging between Objective-C objects and Core Foundation types. Everything was looking good on [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>As I was preparing to post the <a href="https://github.com/tapharmonic/QuartzDemos" title="QuartzDemos">QuartzDemos</a> project on GitHub I decided to modernize the project and covert it to use <a href="http://clang.llvm.org/docs/AutomaticReferenceCounting.html" title="ARC">Automatic Reference Counting</a> (ARC).  Overall this was fairly easy to do despite some of the slightly confusing rules related to bridging between Objective-C objects and Core Foundation types.  Everything was looking good on the Simulator, but decided I should give it a quick once over on the device.  I expected everything to work fine so I launched my first demo and <em>crash</em>!  Hmm&#8230; probably just a debugger anomaly.  So I fired it up again and <em>crash</em>!  The debugging begins&#8230;</p>
<p>I quickly found the cause of the crashes was due to the way I was converting between <code>UIColor</code> and <code>CGColor</code> types.  There were many places where I was using <code>UIColor</code> to produce a <code>CGColorRef</code>,  e.g.:</p>
<pre>// Define Colors
CGColorRef startColor = [UIColor colorWithRed:1.000 green:0.969 blue:0.165 alpha:1.000].CGColor;
CGColorRef endColor = [UIColor colorWithRed:1.000 green:0.400 blue:0.165 alpha:1.000].CGColor;
NSArray *colors = [NSArray arrayWithObjects:(__bridge id)startColor, (__bridge id)endColor, nil];

// Create Gradient
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);</pre>
<p>This code worked fine in a manual memory management case as the <code>UIColor</code> instance gets added to the current autorelease pool which means you can count on it being around for the duration of the current run loop.  However, that behavior is changed when using ARC.  As <code>UIColor</code> is not being assigned anywhere the compiler assumes it&#8217;s not needed and immediately disposes of it.  I was originally planning to go into more detail about why this is happening but noticed a tweet this morning that <a href="http://borkware.com/" title="Mark Dalrymple">Mark Dalrymple</a>, from <a href="http://www.bignerdranch.com/" title="Big Nerd Ranch">The Big Nerd Ranch</a>, beat me to the punch.  Since Mark already did the heavy lifting, I&#8217;ll refer you to <a href="http://weblog.bignerdranch.com/?p=296" title="ARC Gotcha">his post</a> for the details.  Instead, I&#8217;ll cut to the chase and explain how to fix this scenario.</p>
<p>After realizing the cause of the problem implementing a solution was fairly straightforward.  I converted the code above to the following:</p>
<pre>// Define Colors
UIColor *startColor = [UIColor colorWithRed:1.000 green:0.969 blue:0.165 alpha:1.000];
UIColor *endColor = [UIColor colorWithRed:1.000 green:0.400 blue:0.165 alpha:1.000];
NSArray *colors =
    [NSArray arrayWithObjects:(__bridge id)startColor.CGColor, (__bridge id) endColor.CGColor, nil];

CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);</pre>
<p>Instead of defining the start and end colors as <code>CGColorRef</code> I define them as <code>UIColor</code> references and defer getting their underlying Core Graphics equivalent until it&#8217;s actually needed.  This has the effect of extending the lifetime of the <code>UIColor</code> instances long enough to resolve the problem I was running into.</p>
<p>For more examples of this solution in action I&#8217;ll refer you to the <a href="https://github.com/tapharmonic/QuartzDemos" title="QuartzDemos">QuartzDemos</a> project on GitHub.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bobmccune.com/2012/02/28/a-funny-thing-happened-on-the-way-to-the-arc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Drawing with Quartz on iOS</title>
		<link>http://www.bobmccune.com/2012/02/27/drawing-with-quartz-on-ios/</link>
		<comments>http://www.bobmccune.com/2012/02/27/drawing-with-quartz-on-ios/#comments</comments>
		<pubDate>Mon, 27 Feb 2012 00:38:02 +0000</pubDate>
		<dc:creator>Bob McCune</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Quartz]]></category>

		<guid isPermaLink="false">http://www.bobmccune.com/?p=468</guid>
		<description><![CDATA[A couple of weeks ago I gave a presentation entitled &#8220;Drawing with Quartz on iOS&#8221; to the Minnesota CocoaHeads group. We had a big crowd that night and I hope you all enjoyed it. The slide deck is available on SlideShare and the QuartzDemos project is available on Github. Quartz is an essential API for [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>A couple of weeks ago I gave a presentation entitled &#8220;Drawing with Quartz on iOS&#8221; to the <a href="http://cocoaheadsmn.org/" title="MN CocoaHeads">Minnesota CocoaHeads</a> group.  We had a big crowd that night and I hope you all enjoyed it.  The slide deck is available on <a href="http://www.slideshare.net/bobmccune/drawing-with-quartz-on-ios" title="Drawing with Quartz Presentation">SlideShare</a> and the <a href="https://github.com/tapharmonic/QuartzDemos" title="QuartzDemos project on Github">QuartzDemos</a> project is available on Github.</p>
<p>Quartz is an essential API for Mac and iOS developers to know, but I don&#8217;t believe it is widely understood.  There are many useful resources on the Internets, <a href="http://www.raywenderlich.com/" title="Ray Wenderlich">Ray Wenderlich&#8217;s</a> and <a href="http://losingfight.com/blog/">Andy Finnell&#8217;s</a> sites immediately come to mind, but the information on the topic is largely scattered.  I&#8217;m hoping this presentation and sample project help to consolidate some of this information and make it easier for developers to learn the framework.</p>
<p>Feel free to reach out if you have any questions or comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bobmccune.com/2012/02/27/drawing-with-quartz-on-ios/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Screen Capture in iOS Apps</title>
		<link>http://www.bobmccune.com/2011/09/08/screen-capture-in-ios-apps/</link>
		<comments>http://www.bobmccune.com/2011/09/08/screen-capture-in-ios-apps/#comments</comments>
		<pubDate>Thu, 08 Sep 2011 01:44:03 +0000</pubDate>
		<dc:creator>Bob McCune</dc:creator>
				<category><![CDATA[Core Animation]]></category>
		<category><![CDATA[iOS]]></category>

		<guid isPermaLink="false">http://www.bobmccune.com/?p=423</guid>
		<description><![CDATA[I occasionally come across the need to grab the contents of a view as an image. This is often the result of needing to perform some non-stock, animated transition between views, but there are a variety of reasons why this might be useful. Thanks to the Core Animation framework&#8217;s CALayer class, this is easy to [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I occasionally come across the need to grab the contents of a view as an image. This is often the result of needing to perform some non-stock, animated transition between views, but there are a variety of reasons why this might be useful. Thanks to the Core Animation framework&#8217;s <code>CALayer</code> class, this is easy to do.</p>
<p>All <code>UIView</code> instances have an underlying instance of a <code>CALayer</code>. The layer is responsible for rendering the view&#8217;s contents and performing any view-related animations. CALayer defines a method called <code>renderInContext:</code> which allows you to render the layer, and its sublayers, into a given graphics context:</p>
<pre>
UIGraphicsContext context = // some graphics context
[viewToCapture.layer renderInContext:context];
</pre>
<p>Before you can access any layer-specific APIs, you&#8217;ll need to make sure you&#8217;re linking against the QuartzCore framework. Xcode&#8217;s default templates don&#8217;t link against this framework so you&#8217;ll need to select <em>Target Name</em> &gt; Build Phases &gt; Link Binary With Libraries and select <code>QuartzCore.framework</code>.</p>
<p><img src="http://www.bobmccune.com/wp-content/uploads/2011/09/xcode_linking.png" alt="" title="xcode_linking" width="597" height="278" class="alignnone size-full wp-image-435" /></p>
<p>Additionally, you&#8217;ll need to add the following import to your code wherever you are calling the layer&#8217;s properties or methods:</p>
<pre>#import &lt;QuartzCore/QuartzCore.h&gt;</pre>
<p>With the necessary project configuration out of the way, the next question is where do we get a graphics context into which we can render the view&#8217;s content? This can be created using UIKit&#8217;s <code>UIGraphicsBeginImageContextWithOptions</code> function which will create a new bitmap-based graphics context for us.</p>
<pre>UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);</pre>
<p>This function takes a <code>CGSize</code> (you view&#8217;s size), a <code>BOOL</code> indicating if your view is opaque, and a <code>CGFloat</code> specifying the scaling factor. If you&#8217;re rendering a fully opaque, rectangular view you can pass YES for the <code>opaque</code> argument so the alpha channel can be discarded from the context.</p>
<p>Now that we&#8217;ve created a graphics context we can use the <code>UIGraphicsGetCurrentContext()</code> and <code>UIGraphicsGetImageFromCurrentImageContext()</code> functions to get reference to this new context and retrieve the rendered image data from it. Finally, we&#8217;ll want to call the <code>UIGraphicsEndImageContext()</code> function to clean up this context and remove it from the stack. Putting all this together we end up with the following:</p>
<pre>// Render the views layer contents into the current Graphics context
CGSize viewSize = viewToCapture.bounds.size;
UIGraphicsBeginImageContextWithOptions(viewSize, NO, 1.0);
[viewToCapture.layer renderInContext:UIGraphicsGetCurrentContext()];
// Read the UIImage object
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
</pre>
<p>To see this code in action I&#8217;ve put together a simple demo app. You can tap on Archer, Lana, or the background to capture the contents of the view and write the image to your Photo Library.</p>
<p><img src="http://www.bobmccune.com/wp-content/uploads/2011/09/archerlana.png" alt="" title="archerlana" width="500" height="350" class="alignnone size-full wp-image-438" /></p>
<p><strong>Note:</strong> Before running the demo be sure to open the &#8220;Photos&#8221; app on the Simulator so it can initialize its database or the images won&#8217;t be written. Enjoy!</p>
<p><a href='http://www.bobmccune.com/wp-content/uploads/2011/09/SnapMe.zip'>Download Demo</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.bobmccune.com/2011/09/08/screen-capture-in-ios-apps/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Quick Github PSA</title>
		<link>http://www.bobmccune.com/2011/09/06/quick-github-psa/</link>
		<comments>http://www.bobmccune.com/2011/09/06/quick-github-psa/#comments</comments>
		<pubDate>Tue, 06 Sep 2011 06:38:09 +0000</pubDate>
		<dc:creator>Bob McCune</dc:creator>
				<category><![CDATA[Core Animation]]></category>
		<category><![CDATA[iOS]]></category>

		<guid isPermaLink="false">http://www.bobmccune.com/?p=416</guid>
		<description><![CDATA[My Core Animation Demos projects was previously available on Github under my personal account, but I have since moved it to my business account. The new location of of the CA demos is: https://github.com/tapharmonic/Core-Animation-Demos I haven&#8217;t made any major changes to code at this point, however, I did start an ARC branch to house my [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>My Core Animation Demos projects was previously available on Github under my personal account, but I have since moved it to my business account.  The new location of of the CA demos is:</p>
<p><a href="https://github.com/tapharmonic/Core-Animation-Demos">https://github.com/tapharmonic/Core-Animation-Demos</a></p>
<p>I haven&#8217;t made any major changes to code at this point, however, I did start an ARC branch to house my ongoing ARC changes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bobmccune.com/2011/09/06/quick-github-psa/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automagic Factories in Objective-C</title>
		<link>http://www.bobmccune.com/2011/04/08/automagic-factories-in-objective-c/</link>
		<comments>http://www.bobmccune.com/2011/04/08/automagic-factories-in-objective-c/#comments</comments>
		<pubDate>Fri, 08 Apr 2011 14:00:39 +0000</pubDate>
		<dc:creator>Bob McCune</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.bobmccune.com/?p=374</guid>
		<description><![CDATA[The Factory pattern is a frequently used creational pattern to help abstract the creation of an object from its clients. Although there are a few specializations of this pattern I&#8217;ll focus on the most commonly used approach and then look at how we can leverage the Objective-C Runtime to make this solution more robust. Let&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p></p><p><img src="http://www.bobmccune.com/wp-content/uploads/2011/04/magic_hat.png" alt="" title="magic_hat" width="150" height="150" class="alignright size-full wp-image-377" />The <a href="http://www.oodesign.com/factory-pattern.html">Factory</a> pattern is a frequently used <a href="http://www.oodesign.com/creational-patterns/">creational pattern</a> to help abstract the creation of an object from its clients.  Although there are a few specializations of this pattern I&#8217;ll focus on the most commonly used approach and then look at how we can leverage the <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Introduction/Introduction.html">Objective-C Runtime</a> to make this solution more robust.</p>
<p>Let&#8217;s begin by creating a simple command-line app that creates <code>Animal</code> objects and gets them to speak on command.  The various animal objects will all inherit from the <em>abstract</em> <code>Animal</code> class.<br />
<span id="more-374"></span></p>
<pre>
@interface Animal : NSObject {
}

- (void)speak;
- (NSString *)key;

@end
</pre>
<pre>
@implementation Animal

- (void)speak {
    NSAssert(NO, @"The 'speak' method must be implemented by subclass.");
}

- (NSString *)key {
    // Animal instances will be 'keyed' by their lower case class name
    // Overly simplistic, but will suffice for now
    return [NSStringFromClass([self class]) lowercaseString];
}

@end
</pre>
<p>With the abstract base class complete let&#8217;s create a couple concrete <code>Animal</code> implementations:</p>
<pre>
@implementation Cat
- (void)speak {
    NSLog(@"Meow, Meow...");
}
@end
</pre>
<pre>
@implementation Dog
- (void)speak {
    NSLog(@"Bark, Bark...");
}
@end
</pre>
<p>Our <code>Cat</code> &amp; <code>Dog</code> objects are ready to go so let&#8217;s integrate them into our app and get them to speak.</p>
<pre>
int main (int argc, const char * argv[]) {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    Animal *cat = [[Cat alloc] init];
    [cat speak];
    [cat release];

    Animal *dog = [[Dog alloc] init];
    [dog speak];
    [dog release];

    [pool drain];
    return 0;
}
</pre>
<p>Running this app will produce the following console output:</p>
<pre>
Meow, Meow...
Bark, Bark...
</pre>
<p>This works as we&#8217;d expect, but the main problem with using the <code>Cat</code> and <code>Dog</code> classes this way is <em>coupling</em>.  Even though we&#8217;ve defined our variables as abstract <code>Animal</code> types we&#8217;re still coupled to the specific subtypes.  This means we can&#8217;t modify our <code>Animal</code> types or evolve their creation without impacting our client code.  This may seem like a trivial matter in this example, but these design decisions can have major impacts on real-world applications.  Let&#8217;s avoid some of the potential ripple effects by introducing a <em>factory</em>.</p>
<h2>Creating Animals</h2>
<p>We&#8217;ll begin by moving the object creation responsibilities from our client to a new object called <code>AnimalFactory</code>.  This factory, as you may have guessed, will be responsible for creating and vending instances of <code>Animal</code>.  A simple, but common implementation of this could be defined as follows:</p>
<pre>
@implementation AnimalFactory

+ (AnimalFactory *)factory {
    return [[[[self class] alloc] init] autorelease];
}

- (Animal *)animalForKey:(NSString *)animalKey {
    Animal *animal = nil;
    if ([animalKey isEqualToString:@"dog"]) {
        animal = [[Dog alloc] init];
    } else if ([animalKey isEqualToString:@"cat"]) {
        animal = [[Cat alloc] init];
    } else {
        NSAssert(NO, @"No Animal found for key:'%@'", animalKey);
    }
    return [animal autorelease];
}

@end
</pre>
<p>The <code>AnimalFactory</code> will determine which instance to create based on the argument passed to the <code>animalForKey:</code> method.  It creates the appropriate instance and returns an <em>autoreleased</em> version of it to the client.  To use this new factory in our client we can make the following changes:</p>
<pre>
AnimalFactory *factory = [AnimalFactory factory];

[[factory animalForKey:@"cat"] speak];
[[factory animalForKey:@"dog"] speak];
</pre>
<p>If you were to run this example again you would see the same output as before, but the introduction of this factory has helped us resolve two specific limitations in our previous implementation:</p>
<ol>
<li>The client is no longer coupled to a particular instance of <code>Animal</code>.  As our requirements change the factory can return alternate instances (<code>FatCat</code>, <code>HotDog</code>, etc.) without impacting our client code.</li>
<li>The client is no longer in the business of object creation which means <em>how</em> an animal is instantiated is no longer its concern.  Additionally, by returning an autoreleased instance we don&#8217;t unnecessarily force memory management responsibilities onto the client.</li>
</ol>
<p>One outstanding problem we have is with the factory itself.  Although the client is better decoupled from the specific types and their creation, the factory itself is not.  Every time we add a new animal to the app we additionally have to make modifications to the factory.  </p>
<blockquote><p>
    <span style="foreground-color: darkGray"><em>[Informercial Guy Voice]</em></span>&nbsp;&nbsp;<strong>There&#8217;s got to be a better way!</strong>
</p></blockquote>
<h2>Enter the Objective-C Runtime</h2>
<p>
Objective-C is a dynamic language where many decisions are deferred until runtime.  This deferment allows for some of the more interesting capabilities of the language and is made possible through the <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html">Objective-C Runtime</a>.  Although you can successfully use Objective-C without having much awareness of the runtime, understanding how to interact with it can open up some interesting new possibilities.  </p>
<p>
It would be nice if our <code>AnimalFactory</code> could automatically find and dispense all instances of <code>Animal</code> without us having to continuously modify the factory.  Thanks to the runtime, it can.</p>
<h2>Automagic Factories</h2>
<p>Let&#8217;s begin by creating a utility class called <code>RuntimeUtils</code> containing a method to allow us to dynamically find all instances of a particular type.  This method will be implemented as follows:</p>
<pre>
+ (NSArray *)classStringsForClassesOfType:(Class)filterType {

    int numClasses = 0, newNumClasses = objc_getClassList(NULL, 0);
    Class *classList = NULL;

    while (numClasses < newNumClasses) {
        numClasses = newNumClasses;
        classList = realloc(classList, sizeof(Class) * numClasses);
        newNumClasses = objc_getClassList(classList, numClasses);
    }

    NSMutableArray *classesArray = [NSMutableArray array];

    for (int i = 0; i < numClasses; i++) {
        Class superClass = classList[i];
        do {
            // recursively walk the inheritance hierarchy
            superClass = class_getSuperclass(superClass);
            if (superClass == filterType) {
                [classesArray addObject:NSStringFromClass(classList[i])];
                break;
            }
        } while (superClass);
    }

    free(classList);

    return classesArray;
}
</pre>
<p>This method makes use of two functions defined in <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html"><code>&lt;objc/runtime.h&gt;</code></a>:</p>
<ol>
<li><code>objc_getClassList</code> - This function returns a list of all classes registered with the app.  We'll loop through this list and then filter its results.</li>
<li><code>class_getSuperclass</code> - Returns the superclass of a class.  We recursively walk the inheritance hierarchy of each class to determine if it's a descendant of <code>Animal</code>.  If so, we add its class string to our array.
</ol>
<p>With our <code>RuntimeUtils</code> class now ready, let's go back and revisit the implementation of our factory object.</p>
<h2>Implementing the Magic</h2>
<p>We'll change the implementation of our factory class to leverage this new <code>RuntimeUtils</code> class.  We'll start by implementing the <code>init</code> method.</p>
<pre>
- (id)init {
  if ((self = [super init])) {
    NSArray *animalClassStrings = [RuntimeUtils classStringsForClassesOfType:[Animal class]];
    animals = [[NSMutableDictionary alloc] initWithCapacity:[animalClassStrings count]];
      for (id classString in animalClassStrings) {
        Class animClass = NSClassFromString(classString);
        Animal *animal = [[animClass alloc] init];
        [animals setObject:animal forKey:[animal key]];
        [animal release];
      }
    }
  return self;
}
</pre>
<p>Our <code>init</code> implementation starts by finding all the class strings for the classes extending <code>Animal</code>.  We iterate through the results creating an instance of each class and storing its pointer in the <code>animals</code> dictionary.  With the <code>init</code> method complete let's modify the <code>animalForKey:</code> method.</p>
<pre>
- (Animal *)animalForKey:(NSString *)animalKey {
    Animal *animal = [animals objectForKey:animalKey];
    NSAssert(animal, @"No animal found.  Invalid 'animalType' specified?");
    return animal;
}
</pre>
<p>We now have a greatly simplified <code>animalForKey:</code> method.  Gone are the <code>if/else</code> or <code>switch</code> statements you'd typically see in a factory method.  Instead, we have a simple, generic execution path regardless of the number of animals we add to the application.</p>
<p>To see the benefits of our revamped <code>AnimalFactory</code>, let's make a couple additions to our animal kingdom.</p>
<pre>
@implementation Monkey
- (void)speak {
    NSLog(@"Ooo, Ooo, Eee, Eee");
}
@end
</pre>
<pre>
@implementation Bird
- (void)speak {
    NSLog(@"Tweet, tweet");
}
@end
</pre>
<p>We can go back to our client code and make the following changes:</p>
<pre>
[[factory animalForKey:@"dog"] speak];
[[factory animalForKey:@"cat"] speak];
<strong>[[factory animalForKey:@"monkey"] speak];</strong>
<strong>[[factory animalForKey:@"bird"] speak];</strong>
</pre>
<p>If you run the application again you'll see the new <code>Monkey</code> and <code>Bird</code> instances were automatically registered with the factory without any additional changes!  Winning!</p>
<h2>Conclusion</h2>
<p>Although this was clearly a contrived example, it hopefully illustrates how leveraging the Objective-C Runtime can result in significantly more flexible factory objects.  Some simple modifications could be made to this approach to provide for lazy instantiation or handle more complex object creation.  In a future post I'll provide a more concrete example of how this strategy can be put to good use in a real-world application.</p>
<h2>Resources</h2>
<p><a href="http://www.bobmccune.com/wp-content/uploads/2011/04/AutomagicFactories.zip">Sample Code</a></br><br />
<a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html">Objective-C Runtime Reference</a></br><br />
<a href="http://cocoasamurai.blogspot.com/2010/01/understanding-objective-c-runtime.html">Understanding the Objective-C Runtime</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.bobmccune.com/2011/04/08/automagic-factories-in-objective-c/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Core Animation Presentation</title>
		<link>http://www.bobmccune.com/2011/03/13/core-animation-presentation/</link>
		<comments>http://www.bobmccune.com/2011/03/13/core-animation-presentation/#comments</comments>
		<pubDate>Sun, 13 Mar 2011 00:22:48 +0000</pubDate>
		<dc:creator>Bob McCune</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Core Animation]]></category>
		<category><![CDATA[iOS]]></category>

		<guid isPermaLink="false">http://www.bobmccune.com/?p=320</guid>
		<description><![CDATA[This past week I gave a presentation on Core Animation to the Minnesota CocoaHeads user group. Core Animation is a truly amazing framework and is really the magic ingredient in the iOS user experience. Understanding how to effectively use it can allow you to add new levels of realism and interactivity to your apps. As [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>This past week I gave a presentation on <a href="http://developer.apple.com/technologies/ios/graphics-and-animation.html">Core Animation</a> to the <a href="http://www.cocoaheadsmn.org/">Minnesota CocoaHeads</a> user group.  Core Animation is a truly amazing framework and is really the magic ingredient in the iOS user experience.  Understanding how to effectively use it can allow you to add new levels of realism and interactivity to your apps.</p>
<p>As part of the presentation I prepared a number of examples ranging from image effects to 3D animations (OK, 2 1/2 D animations).  If you&#8217;re interested in taking a look you can find the demo on <a href="https://github.com/bobmccune/Core-Animation-Demos">github</a> and the slides are available <a href="http://www.bobmccune.com/works/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bobmccune.com/2011/03/13/core-animation-presentation/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic (Feed is rejected)
Page Caching using disk: enhanced
Database Caching using disk: basic
Object Caching 736/756 objects using disk: basic

Served from: www.bobmccune.com @ 2012-05-18 16:55:05 -->
