<?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>Cocoa Is My Girlfriend &#187; Coding Practice</title>
	<atom:link href="http://www.cimgf.com/category/coding-practice/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cimgf.com</link>
	<description>Taglines are for Windows programmers</description>
	<lastBuildDate>Thu, 15 Jul 2010 21:20:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>My current Prefix.pch file</title>
		<link>http://www.cimgf.com/2010/05/02/my-current-prefix-pch-file/</link>
		<comments>http://www.cimgf.com/2010/05/02/my-current-prefix-pch-file/#comments</comments>
		<pubDate>Mon, 03 May 2010 00:58:32 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Development Environment]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[``]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=977</guid>
		<description><![CDATA[I have posted and discussed this file a few times but as with all things it has been touched, tweaked, and generally improved upon. In this article we will discuss the latest iteration of my Prefix.pch file. As with anything I post, it is available for you to use as you see fit. The File [...]]]></description>
			<content:encoded><![CDATA[<p>I have posted and discussed this file a few times but as with all things it has been touched, tweaked, and generally improved upon.</p>

<p>In this article we will discuss the latest iteration of my <code>Prefix.pch</code> file.  As with anything I post, it is available for you to use as you see fit.</p>

<h2>The File</h2>

<p>For those who don&#8217;t want to read the entire post, here is the file:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#ifdef DEBUG</span>
  <span style="color: #6e371a;">#define DLog(...) NSLog(@&quot;%s %@&quot;, __PRETTY_FUNCTION__, [NSString stringWithFormat:__VA_ARGS__])</span>
  <span style="color: #6e371a;">#define ALog(...) [[NSAssertionHandler currentHandler] handleFailureInFunction:[NSString stringWithCString:__PRETTY_FUNCTION__ encoding:NSUTF8StringEncoding] file:[NSString stringWithCString:__FILE__ encoding:NSUTF8StringEncoding] lineNumber:__LINE__ description:__VA_ARGS__]</span>
<span style="color: #6e371a;">#else</span>
  <span style="color: #6e371a;">#define DLog(...) do { } while (0)</span>
  <span style="color: #6e371a;">#ifndef NS_BLOCK_ASSERTIONS</span>
    <span style="color: #6e371a;">#define NS_BLOCK_ASSERTIONS</span>
  <span style="color: #6e371a;">#endif</span>
  <span style="color: #6e371a;">#define ALog(...) NSLog(@&quot;%s %@&quot;, __PRETTY_FUNCTION__, [NSString stringWithFormat:__VA_ARGS__])</span>
<span style="color: #6e371a;">#endif</span>
&nbsp;
<span style="color: #6e371a;">#define ZAssert(condition, ...) do { if (!(condition)) { ALog(__VA_ARGS__); }} while(0)</span></pre></td></tr></table></div>


<p>This does not <em>replace</em> the Prefix.pch that comes with your project but it does go at the top of every project that I work on.  The rest of this post we will review what this does.
<span id="more-977"></span></p>

<h2><code>#ifdef DEBUG</code></h2>

<p>I normally run my code in one of two modes.  Either I am writing and testing the code or I am compiling it to hand over to QA, a user or Apple (btw I consider all three of those to be synonymous when it comes to builds).  Therefore the first line is a switch to see if we are in debug mode.  I set this value in the build settings of my project.  If you look under the &#8220;Preprocessor Macros&#8221; section you can set the <code>DEBUG</code> definition there.</p>

<h2><code>#define DLog(...)</code></h2>

<p>This is the most used macro I have in my <code>Prefix.pch</code> file.  This is simply <code>NSLog</code> as we know it and love it.  However I automatically prepend the included macro <code>__PRETTY_FUNCTION__</code> so that any log statement that comes out will declare where it is being called from.  Personally I hate having to track down which &#8220;Fix Me&#8221; just spit out to the Console.</p>

<p>The nice thing about <code>DLog</code> over <code>NSLog</code> is that in the other branch this is a no-op that will be removed by the compiler.  Therefore when I do a client build they won&#8217;t see the debug statements nor will their build be slowed down by any potential conditional logic around the debug statements.</p>

<h2><code>#define ALog(...)</code></h2>

<p>While I do not use this one very often I do like this one an awful lot.  When I am in <code>DEBUG</code> mode it will throw an <code>NSAssertion</code> when it gets hit. This is similar to a common line of code that I see:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;">NSAssert<span style="color: #002200;">&#40;</span><span style="color: #a61390;">NO</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;It failed&quot;</span><span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>


<p>or if you want to see the variables:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;">NSAssert2<span style="color: #002200;">&#40;</span><span style="color: #a61390;">NO</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;It failed. Value1: %i Value2: %i&quot;</span>, value1, value2<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>


<p>My version does not have the condition before hand and can take any number of parameters.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;">ALog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;It failed. Value1: %i Value2: %i&quot;</span>, value1, value2<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>


<p>In addition, when the <code>DEBUG</code> flag is not set, this assertion turns into a <code>NSLog</code> which remains visible.  This allows me to have &#8220;This will never happen&#8221; calls in my code that will explode when I hit them but will be more polite if a user hits them but not so polite that I am left wondering what happened.  They won&#8217;t intentionally crash the application but they will leave a fingerprint in the output from the application so that I can discover what happened.</p>

<h2><code>NS_BLOCK_ASSERTIONS</code></h2>

<p>I am of the school of thought that believes you should never throw an assertion in production code.  If your code cannot handle that part of your app being hit and survive in some form or another then it is not production ready.  Simple as that.  Therefore I turn them off in production builds.</p>

<p>However, some other people who write libraries that I depend upon also feel this way.  Therefore I need to check to see if it is already defined so that I can avoid a warning about resetting it.  Since I have warnings set as errors in my code this is needed.</p>

<h2><code>#define ZAssert(condition, ...)</code></h2>

<p>The final gem in this collection is <code>ZAssert</code>.  This is my personal favorite and it lets me clean up my code very nicely.  First, <code>ZAssert</code> is a condition check.  If you pass the check nothing happens.  If you fail the check, bad things happen.  This is just like <code>NSAssert</code> except for one big difference.  When you turn off assertions, <code>NSAssert</code> goes away completely.  This is not what I want to happen in my code.  Instead, when assertions are turned off, I want a failure of this check to turn into an <code>NSLog</code>.  That is what <code>ZAssert</code> does for us.  In this way, we can clean up our code very nicely.  Picture this very common block of code:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>managedObjectContext save<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
  NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;My save failed: %@<span style="color: #2400d9;">\n</span>%@&quot;</span>, <span style="color: #002200;">&#91;</span>error localizedDescription<span style="color: #002200;">&#93;</span>, <span style="color: #002200;">&#91;</span>error userInfo<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
  <span style="color: #a61390;">abort</span><span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>That is a LOT of code just to perform a save!  Blocks of code like this are very common in Objective-C.  Unfortunately we can&#8217;t roll this up into a <code>NSAssert</code> because the entire line of code will disappear when we turn them off.</p>

<p>With <code>ZAssert</code> it gets a lot cleaner:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
ZAssert<span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>managedObjectContext save<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;My save failed: %@<span style="color: #2400d9;">\n</span>%@&quot;</span>, <span style="color: #002200;">&#91;</span>error localizedDescription<span style="color: #002200;">&#93;</span>, <span style="color: #002200;">&#91;</span>error userInfo<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>


<p>Because ZAssert survives when <code>NS_BLOCK_ASSERTIONS</code> is set and simply mutates, we can inline the save directly and make the code a lot easier to read.</p>

<h1>Wrap Up</h1>

<p>I am sure this code will evolve.  When it has changed significantly I will do an updated post.  If anyone else has some nice tips for the <code>Prefix.pch</code> then please share them as we all benefit.</p>

<h1>Acknowledgements</h1>

<p>First I would like to recognize Fraser Hess who did the original post and showed me what we can do with macros.</p>

<p>Second I would like to point out that the NSAssert line of code above is borrowed heavily from BareBones software. They figured out how to generate an assertion without actually using the <code>NSAssert</code> macros.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2010/05/02/my-current-prefix-pch-file/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Creating a NSManagedObject that is Cross Platform</title>
		<link>http://www.cimgf.com/2010/02/18/creating-a-nsmanagedobject-that-is-cross-platform/</link>
		<comments>http://www.cimgf.com/2010/02/18/creating-a-nsmanagedobject-that-is-cross-platform/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 18:37:33 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[iPod Touch]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=950</guid>
		<description><![CDATA[An interesting question came up on Stackoverflow today so I decided to expound upon it in a short blog post. A situation that I believe we are going to be seeing more and more often is one where application developers are writing multiple &#8220;versions&#8221; of their applications to be used on the desktop, their iPhone [...]]]></description>
			<content:encoded><![CDATA[<p>An interesting question came up on Stackoverflow today so I decided to expound upon it in a short blog post.</p>

<p>A situation that I believe we are going to be seeing more and more often is one where application developers are writing multiple &#8220;versions&#8221; of their applications to be used on the desktop, their iPhone and now the iPad.</p>

<p>Because of that situation, it is becoming even more important that we write as much portable code as possible.  Fortunately, our model can be completely portable between the two platforms.</p>

<p><span id="more-950"></span></p>

<h2>NSImage vs UIImage</h2>

<p>The primary issue with creating a portable model and model objects is images.  Now, if the images are stored on disk and only referenced in your Core Data model, then you don&#8217;t have an issue.  Since you are storing the images on disk in a portable format (png, jpeg, etc.) then they will port right over to all of the platforms you are targeting.</p>

<p>But what happens when you are working with small images that should be stored within Core Data?  Simple right, just use a transformable data type and stick the image right in there.</p>

<p>Unfortunately that fails in the portability department.</p>

<p>The issue is that on the desktop you are storing a serialized version of the NSImage instance and on the other devices you are storing an instance of UIImage.  Two different data structures that are incompatible.  So what is the right answer?</p>

<p>Store the images in a portable format even in Core Data.</p>

<p>But that is hard right?</p>

<p>Fortunately if we create concrete subclasses of any entity that needs to store images it is a small amount of code and some conditional compiling.</p>

<h3><code>MyEntityWithAnImage.h</code></h3>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;">&nbsp;
<span style="color: #a61390;">@interface</span> MyEntityWithAnImage <span style="color: #002200;">:</span> <span style="color: #400080;">NSManagedObject</span>
<span style="color: #002200;">&#123;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #6e371a;">#ifdef IPHONEOS_DEPLOYMENT_TARGET</span>
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</span> UIImage <span style="color: #002200;">*</span>image;
<span style="color: #6e371a;">#else</span>
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</span> <span style="color: #400080;">NSImage</span> <span style="color: #002200;">*</span>image;
<span style="color: #6e371a;">#endif</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>


<p>In the header we declare the same property and the use some conditional compiling to determine which definition should be used.  On the desktop the property image will return an NSImage and on the other platforms it will return a UIImage.  But how do we work this magic?</p>

<h3><code>MyEntityWithAnImage.m</code></h3>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#ifdef IPHONEOS_DEPLOYMENT_TARGET</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setImage<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIImage<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>self willChangeValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>data <span style="color: #002200;">=</span> UIImagePNGRepresentation<span style="color: #002200;">&#40;</span>image<span style="color: #002200;">&#41;</span>;
  <span style="color: #002200;">&#91;</span>myManagedObject setImage<span style="color: #002200;">:</span>data<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self setPrimitiveValue<span style="color: #002200;">:</span>data forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self didChangeValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>UIImage<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>self willAccessValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  UIImage <span style="color: #002200;">*</span>image <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIImage imageWithData<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self primitiveValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self didAccessValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">return</span> image;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #6e371a;">#else</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setImage<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSImage</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>self willChangeValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #400080;">NSBitmapImageRep</span> <span style="color: #002200;">*</span>bits <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>image representations<span style="color: #002200;">&#93;</span> objectAtIndex<span style="color: #002200;">:</span> <span style="color: #2400d9;">0</span><span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #400080;">NSData</span> <span style="color: #002200;">*</span>data <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>bits representationUsingType<span style="color: #002200;">:</span>NSPNGFileType properties<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>myManagedObject setImage<span style="color: #002200;">:</span>data<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self setPrimitiveValue<span style="color: #002200;">:</span>data forKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self didChangeValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSImage</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>self willAccessValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #400080;">NSImage</span> <span style="color: #002200;">*</span>image <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSImage</span> alloc<span style="color: #002200;">&#93;</span> initWithData<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self primitiveValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>self didAccessValueForKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;image&quot;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>image autorelease<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #6e371a;">#endif</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>


<p>Here we are overriding the dynamic accessors and implementing our own.  We are fully KVO compliant and notify when we are accessing or changing the image value.</p>

<p>In the desktop version we grab the bitmap image representation and then get the PNG representation of it and store that representation into Core Data as NSData.</p>

<p>In the Cocoa Touch version we are using the C function which returns the PNG representation of the UIImage instance directly.  We are again storing that as NSData into our image property.</p>

<p>In both cases the getter reverses the process by loading the NSData back into the appropriate image instance.</p>

<h2>Wrap Up</h2>

<p>This makes the code external to our <code>NSManagedObject</code> completely unaware of the actual data storage and they just know that they are getting back the object they need to work with.</p>

<p>BTW, if anyone knows of another pre-processor variable that I should be using for this instead of <code>IPHONEOS_DEPLOYMENT_TARGET</code> please let me know.  I am not 100% confident that <code>IPHONEOS_DEPLOYMENT_TARGET</code> is the best variable to be testing against.</p>

<p>Do you like this idea, hate it?  Tell me in person at <a href='http://nsconference.com/'>NSConferenceUSA</a>!  Tickets are still available and it will be great to see you there.</p>

<p>If that is too soon then please catch me at <a href='http://360idev-MarcusZ.eventbrite.com/'>360 iDev</a> in April!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2010/02/18/creating-a-nsmanagedobject-that-is-cross-platform/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Cocoa Tutorial: Creating your very own framework</title>
		<link>http://www.cimgf.com/2008/09/04/cocoa-tutorial-creating-your-very-own-framework/</link>
		<comments>http://www.cimgf.com/2008/09/04/cocoa-tutorial-creating-your-very-own-framework/#comments</comments>
		<pubDate>Thu, 04 Sep 2008 18:05:25 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=229</guid>
		<description><![CDATA[There are numerous situations where creating your own framework is advantageous. Perhaps you have a block of code that you use repeatedly in many different projects. Perhaps you are building a plug-in system for your application and want the infrastructure to be available both to the application and to any plugins that are coded. A [...]]]></description>
			<content:encoded><![CDATA[<p>There are numerous situations where creating your own framework is advantageous.  Perhaps you have a block of code that you use repeatedly in many different projects.  Perhaps you are building a plug-in system for your application and want the infrastructure to be available both to the application and to any plugins that are coded.</p>

<p>A Cocoa framework is another project type in Xcode.  The end result is a bundle, similar to an application bundle.  Inside of this bundle is the compiled code you wrote and any headers that you want exposed.  The headers are important.  Without them, just like any other piece of Objective-C code, it is very hard to code against.</p>

<p><span id="more-229"></span></p>

<h2>Building a Framework in Xcode</h2>

<p>Building a framework within Xcode is straight-forward.  There is already a project template specifically for Cocoa frameworks so that is where we will start.</p>

<div style="text-align:center;"> <a href="http://www.cimgf.com/wp-content/uploads/2008/09/newframework.png" rel="lightbox" title="New Framework Project"><img src="http://www.cimgf.com/wp-content/uploads/2008/09/newframework.png" width="250"alt="New Framework Project" /></a></div>

<p>Once the framework is build, the rest of the code development is almost identical to an application bundle.  C, C++ and Objective-C files can be included along with nibs, xibs, images and just about anything else we would stick into an application bundle.  When the code is complied, the end result is also a bundle, again very similar to an application.  The bundle structure, however, is a bit different and will be discussed in detail below.</p>

<p>Care must be given to the headers that we write and that we expose as part of that framework.  In general, we really only want to expose the headers that users of the framework are going to interact with.  If a header is completely internal to the framework then do not plan on exposing it.  In addition, it is a good idea to have a wrapper header that users can import and gain references to all of the public headers.  Since a framework will undoubtably contain more than one class file, how do we roll all of that up into one header?  One solution I have seen is to create a separate header file and copy all of the interfaces into it.  Unfortunately that solution can become unwieldy very quickly.  My preferred solution is to build a &#8220;wrapper&#8221; header file that imports all of the headers that you want exposed.  This is demonstrated in <i>Code Sample 1</i>.</p>

<hr/>

<p><small><strong><i>Code Sample 1: Example.h</i></strong></small></p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &quot;ExampleOne.h&quot;</span>
<span style="color: #6e371a;">#import &quot;ExampleTwo.h&quot;</span></pre></div></div>


<p>Once the framework is built but before we distribute it, there are a few tweaks we need to deal with.  First, we need to declare which headers are public and which are project.  There is also an option for private but honestly I cannot see the logic behind them.  If we flag a header as private it gets included in the resulting framework in a directory called &#8220;PrivateHeaders&#8221;.  However, if we flag a header as &#8220;project&#8221; then it is correctly not included in the framework.  Public headers are naturally included in the framework under the Headers directory.</p>

<h2>Which headers should be included</h2>

<p>&lt;</p>

<p>p>For some headers, the answer to that question is easy.  However, there are some gotchas that need to be planned around.  If an object is referenced in one of the public headers then its header must also be public.  Therefore if we want an object to be private/hidden/internal then we need to make sure there are no public references to it anywhere in any of the exposed headers.  For example, if we had a an internal object called InternalObject and we referenced it in our header, the header for InternalObject would need to be public.  See See <em>Image 2</em>.</p>

<div style="text-align:center;"> <a href="http://www.cimgf.com/wp-content/uploads/2008/09/allpublic.png" rel="lightbox" title="All Public Headers"><img src="http://www.cimgf.com/wp-content/uploads/2008/09/allpublic.png" width="250"alt="All Public Headers"/></a></div>

<p>&lt;</p>

<p>p>However, if the reference is an <em>id</em> instead, we can keep the InternalObject private and its header un-exposed.  See <em>Image 3</em>.</p>

<div style="text-align:center;"> <a href="http://www.cimgf.com/wp-content/uploads/2008/09/projectinternal.png" rel="lightbox" title="Project Level InternalObject"><img src="http://www.cimgf.com/wp-content/uploads/2008/09/projectinternal.png" width="250"alt="Project Level InternalObject"/></a></div>

<p>On thing to note is that in both cases, the AbstractExample is public even though we do not want anyone extending it.  Because both ExampleOne and ExampleTwo are subclasses of AbstractExample its header must therefore be included in the framework.  To make this a little confusing, this is NOT the case if the application and the framework both exist in the same project!  If we look at the included project (called Example), and turn AbstractExample to project, everything will work just fine.  However, if we take that compiled framework and use it in the second included project (called Test), it will fail.  Therefore depending on how we are going to use the framework, superclasses will probably need to be included.</p>

<h2>Using the framework</h2>

<p>Now that we have our framework built, how do we use it? There are three places we can put this framework.  We can make it system accessible, user accessible or application accessible.</p>

<h3>System Accessible</h3>

<p>System accessible frameworks are just like the frameworks that come with OS X.  They can be imported into any application.  For this magic to work, however, they need to be installed in a system level folder; specifically /Library/Frameworks.  Go ahed and look in that directory now.  If your system is anything like mine it is empty.  Why?  Because system level frameworks require root access to be installed and therefore require privilege escalation to get them there.  Generally this is a <strong><emph>BAD IDEA</emp></strong> and there are few frameworks that follow this path.</p>

<h3>User Accessible</h3>

<p>User accessible frameworks are very similar to System accessible frameworks.  However they are stored in a user writable location instead; ~/Library/Frameworks.  Go ahead and look for this directory also.  Chances are the directory itself does not even exist.  This is safer than a system accessible framework and if we have a framework that is going to be used by multiple applications then this might be a logical place for it.  But both user accessible frameworks and system frameworks have the same technical challenge discussed below.</p>

<h3>Application Accessible</h3>

<p>Outside of Apple this is the most common usage of a framework.  It is bundled with the application and only the application can access it.  Both of the other locations for frameworks have one issue; how do you get them there?  The answer?  You include them with the application of course!  However, if you have to include them with the application (and you will need to include them with EVERY application that uses them) then what exactly is the point of putting them somewhere else?  This is one of the main reasons that System and User accessible frameworks really don&#8217;t have a point; again outside of Apple.</p>

<h3>Setting the installation directory</h3>

<p>Since it only really makes sense to have our framework be application accessible, we need to tell it that when we build it.  While this is not important for an application that has the framework included in its build cycle, if we want our application to be used by other applications, it becomes critical.  When an application links to a framework, it needs to know where the final resting place of that framework is going to be.  The default for the framework template is ~/Library/Frameworks.  Clearly this needs to change.</p>

<p>To get a framework to acknowledge that it will be used inside of an application, we have to set the installation directory to a relative path.  That relative path is:</p>

<p><pre>
@executable_path/../Frameworks
</pre></p>

<p>Once we have the installation directory set, it is time to include it in our application.</p>

<h3>Setting up the targets for our application</h3>

<p>Looking in the Example project, there are two targets, one for the framework and one for the application.  Opening the application&#8217;s target we can see that the framework is a dependency of the application.  This will insure that the framework will be built whenever we build the application.  In addition, the framework is also in the &#8220;Link Binary With Libraries&#8221; build phase so that our application can build against it.</p>

<div style="text-align:center;"><img src="http://www.cimgf.com/wp-content/uploads/2008/09/apptargets.png" alt="Application Target Structure" border="0" width="229"/></div>

<p>There are also two new build steps for this application that are directly related to the framework.  First, is a Copy Frameworks phase.  This was added using the Project -> New Build Phase -> New Copy Files Build Phase.  I then renamed it to Copy Frameworks for clarity.  Selecting Show Info on the Copy Frameworks build phase will show that its directory is set to &#8220;Frameworks&#8221;.  This will create a Frameworks directory inside of our application build and copy our framework into it.  This is how we distribute a framework with the application.</p>

<p>&lt;</p>

<p>p>The other additional build phase is called &#8220;Clean Framework Headers&#8221; and is a script build phase.  The purpose behind this phase is to delete all of the header files out of the application bundle once everything is finished.  Why?  Because they are not needed at runtime and there is no point in distributing them.  When we distribute the framework on its own we definitely need to leave them but for the included framework they are just wasted bits.  Therefore the script removes them as the final build phase for the application <em>only</em>.  See <em>Code Sample 2</em>.</p>


<div class="wp_syntax"><div class="code"><pre class="perl" style="font-family:monospace;">echo <span style="color: #ff0000;">&quot;build path ${TARGET_BUILD_DIR}&quot;</span>
cd <span style="color: #0000ff;">$</span><span style="color: #009900;">&#123;</span>TARGET_BUILD_DIR<span style="color: #009900;">&#125;</span><span style="color: #339933;">/</span><span style="color: #0000ff;">$</span><span style="color: #009900;">&#123;</span>FULL_PRODUCT_NAME<span style="color: #009900;">&#125;</span><span style="color: #339933;">/</span>Contents<span style="color: #339933;">/</span>Frameworks 
rm <span style="color: #339933;">-</span>rf <span style="color: #339933;">*/</span>Headers 
rm <span style="color: #339933;">-</span>rf <span style="color: #339933;">*/</span>Versions<span style="color: #339933;">/*/</span>Headers 
rm <span style="color: #339933;">-</span>rf <span style="color: #339933;">*/</span>Versions<span style="color: #339933;">/*/</span>PrivateHeaders 
rm <span style="color: #339933;">-</span>rf <span style="color: #339933;">*/</span>Versions<span style="color: #339933;">/*/</span>Resources<span style="color: #339933;">/*/</span>Contents<span style="color: #339933;">/</span>Headers</pre></div></div>


<h2>Framework Structure</h2>

<p>&lt;</p>

<p>p>For the curious, the internal structure of a framework is similar to an application.  There is a compiled binary and a Resources directory that contains all of the xib, nibs, etc.  There is also a Headers directory (and in some cases a PrivateHeaders directory) that contains all of the exposed header files.  Where things chance is that a framework is versionable.  The actual headers, resources and binary are actually stored in the Versions/${VERSION} subdirectory.  From that directory there are sym-links up to the root directory of the bundle and also to the Versions/Current subdirectory.</p>

<p><pre>
${compiled_binary} -> Versions/Current/Example
Headers -> Versions/Current/Headers
Resources -> Versions/Current/Resources
Versions/A/${compiled_binary}
Versions/A/Headers
Versions/A/Resources
Versions/Current -> A
</pre></p>

<p>The purpose of this is to allow multiple versions of a framework to be stored within one bundle.  However it is unlikely you will ever see more than one version in a bundle.  It is a manual process to combine the versions and each version has to be kept in its own xcode project and merged by hand.  In addition, since it really only makes sense to have frameworks inside of application bundles, it does not make much sense to have multiple versions of the framework.  Nevertheless the functionality is there for those pesky edge cases.</p>

<h2>Conclusion</h2>

<p>Frameworks definitely have their place.  They are very useful when writing a plugin architecture, etc.  However, since they only make sense to include them in an application, unless you are sharing the framework or doing plugins, chances are it is better to just include the source code and be done with it.</p>

<p><center></p>

<table>
<tr>
<td><a href="http://www.cimgf.com/wp-content/uploads/2008/09/example.zip" title="Example Project"><img src="http://www.cimgf.com/wp-content/uploads/2008/03/xcode.png" alt="xcode.png" border="0" width="64"/><br/>Example Project</a></td>
<td><a href="http://www.cimgf.com/wp-content/uploads/2008/09/test.zip" title="Test Project"><img src="http://www.cimgf.com/wp-content/uploads/2008/03/xcode.png" alt="xcode.png" border="0" width="64"/><br/>Test Project</a></td>
</tr>
</table>

<p></center></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/09/04/cocoa-tutorial-creating-your-very-own-framework/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Version Control Makes You A Better Programmer</title>
		<link>http://www.cimgf.com/2008/06/03/version-control-makes-you-a-better-programmer/</link>
		<comments>http://www.cimgf.com/2008/06/03/version-control-makes-you-a-better-programmer/#comments</comments>
		<pubDate>Tue, 03 Jun 2008 17:47:45 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Development Environment]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[Version Control]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=130</guid>
		<description><![CDATA[I&#8217;m a believer. I&#8217;ve used version control before, but Marcus has convinced me that with a little known version control system called Git, written by Linus Torvalds (the creator of Linux), version control is not just about versioning, it&#8217;s about expressing yourself with your code and collaborating with others, seamlessly. As memory serves the only [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m a believer. I&#8217;ve used version control before, but Marcus has convinced me that with a little known version control system called <a href="http://www.kernel.org/pub/software/scm/git/docs/tutorial.html">Git</a>, written by <a href="http://en.wikipedia.org/wiki/Linus_Torvalds">Linus Torvalds</a> (the creator of Linux), version control is not just about versioning, it&#8217;s about expressing yourself with your code and collaborating with others, seamlessly.</p>

<p>As memory serves the only time I&#8217;ve used version control in a meaningful way the system I was using was Visual SourceSafe from Microsoft. I know. Blech! It&#8217;s awful! I&#8217;ve <em>pulled</em> code from many a CVS or Subversion repository, but I&#8217;ve never really used them in the way they are intended to be used. Now, thanks to Marcus, I realize that version control isn&#8217;t just about versioning any more. It&#8217;s a whole methodology/ideology that makes better programmers. Here is what I mean.
<span id="more-130"></span></p>

<h2>Branching Inspires Wild Experimentation</h2>

<p>Have you ever been so far down a path in your code that you just think, though you probably should, there is no way you would take a chance to re-factor due to looming deadlines or even just a simple fear that you might mess up so badly you couldn&#8217;t recover? Well, fear no more! Git provides such a simple way to create a branch of your code in which you can experiment, you won&#8217;t even give it a second thought. I won&#8217;t go into the whole setup and how to get going with Git as this is done very well elsewhere <a href="http://www.cimgf.com/2008/03/18/git-and-mac-a-match-made-in-purgatory/">including a previous post from Marcus</a>. I just want to point out how easy it is to branch with a single command. In Terminal.app, <em>cd</em> to the directory of a project you have under Git source control and enter the following command.
<pre>
bash$ git branch experimental
</pre>
That&#8217;s all there is to it. You now have a nice shiny clean slate to experiment with abandon. You simply type:
<pre>
bash$ git checkout experimental
</pre>
and you are now working on the <em>experimental</em> branch you just created. Now you can just run amok and have nothing to worry about. Make crazy experimental changes to your heart&#8217;s content and all you need to do to go back to your original code base is type:
<pre>
bash$ git checkout master
</pre>
and you&#8217;re back in business. If you found that your crazy coding excursion was a great success, you can merge your changes in with the following commands.
<pre>
bash$ git checkout master
bash$ git merge experimental
</pre>
The first command switches you back to the <em>master</em> branch, while the second performs the merge of the code from the <em>experimental</em> branch into the <em>master</em> branch. If there are conflicts, you will have to fix them manually, but it seems that the need to do so is pretty rare. Git does a great job at merging changes automatically.</p>

<p>If you found, conversely, that your ideas were purely delusional&#8211;a characteristic of your over-achieving sense of hubris&#8211;you can blow them away by simply typing:
<pre>
bash$ git branch -d experimental
</pre></p>

<p>Now the idea is just a bad memory and not something you ever need worry about (or mention to your programming peers) again. Your code on the master branch is still as it was when you first started the branch. Hallelujah!</p>

<blockquote><strong>Note:</strong> The word &#8216;experimental&#8217; I&#8217;ve used in these command line examples is simply a tag. You can call your branch whatever you like. Call it &#8216;hubris&#8217; if you like. Depending on your personality, this may be more appropriate.</blockquote>

<p>The chance to experiment so easily and without fear will make you a better programmer. You will venture into areas that you would have never tried before and will likely become more bold in what you&#8217;re willing to attempt. This can only be a good thing in the long run.</p>

<h2>Collaboration</h2>

<p>The <a href="http://www.kernel.org/pub/software/scm/git/docs/tutorial.html">Tutorial introduction to git</a> provides a good example of how to collaborate when multiple people are working on the same computer, but where Git&#8217;s real power comes in is in its ability to enable collaboration. If you&#8217;re familiar with extreme programming or pair programming then you are already aware of how collaboration will make you a better programmer. The learning curve for developing applications for the Macintosh for me has been significantly leveled as Marcus has shown me how to do things in the context of real code. You can learn things in many different ways, but sharing code has got to be one of the strongest means of gaining deeper understanding. This can only make you a better programmer.</p>

<p>While not a direct feature of Git itself, you can share your repository over the many file sharing web applications out there. Marcus and I use <a href="http://www.getdropbox.com/">Dropbox</a> for our projects that we collaborate on. Here are the steps you take to collaborate remotely using Git and Dropbox.</p>

<ol>
<li>Sign up and install Dropbox from <a href="http://www.getdropbox.com/">http://www.getdropbox.com</a>.<br />
<br />This will create a folder in your home directory under <em>~/Dropbox</em>.</li>

<li>Have the person you want to collaborate with do the same and then create a shared folder that both of you can access through the Dropbox web interface.<br /><br /></li>

<li>From the project directory of the project you want to share, type:
<pre>
bash$ git clone --bare . ~/Dropbox/Shared/MySharedProject.git
</pre>
<blockquote>
<strong>Note:</strong> Keep in mind that I&#8217;m assuming you already have this project under Git version control. If not you first need to run init like so in the root of your project directory.
<pre>
bash$ git init
</pre>
</blockquote>

The <strong>&#8211;bare</strong> keyword we used in the clone command means that we simply want to create a directory that contains the contents of the .git directory in your project directory and not the actual workspace. The .git directory contains all of your code and changes to everything you need is there&#8211;it&#8217;s just not the actual workspace where xcode works from. 

</li>
<li>Create a remote (alias) for the newly cloned project by typing:
<pre>
bash$ git remote add sharedproject ~/Dropbox/Shared/MySharedProject.git
</pre>
</li><br />
<li>Now you can push any code changes from your working directory to the cloned directory, which, since it is in your <em>Dropbox</em> will automatically be uploaded to the drop box and downloaded by any other computers you have that can access <em>Dropbox</em>. First you need to commit any changes in your working directory with the following command.
<pre>
bash$ git commit -a -m "Commit message"
</pre>
Then you need to push the changes to the remote with the following.
<pre>
bash$ git push sharedproject master
</pre>
This pushes your changes to the cloned repository which is in your </em>Dropbox</em> directory. As soon as you do this, you should see the <em>Dropbox</em> icon in your menu bar change to the &#8216;synchronizing&#8217; icon. If your change is small, it will only change for a split second so you&#8217;ll have to watch it closely to see that happen.
</li>
</ol>

<p>Once your files are committed and have been pushed to your cloned repository, you can now <em>pull</em> the project from another computer. I&#8217;m assuming you have <em>Git</em> and <em>Dropbox</em> set up on the second computer. Here are the steps you take to get the code into Git.</p>

<ol>
<li>In Terminal.app on your other computer, create a new directory where you want your project to be stored with a working directory. Now run the following command.
<pre>
bash$ git clone ~/Dropbox/Shared/MySharedProject.git
</pre>
Notice that we didn&#8217;t use the <strong>&#8211;bare</strong> keyword this time. This is because we want our cloned copy to also setup a working directory since we&#8217;ll be accessing it from xcode on the second computer as well.
</li>
<li>Now create a remote (alias) to reference the project like you did on the other computer using the following.
<pre>
bash$ git remote add sharedproject ~/Dropbox/Shared/MySharedProject.git
</pre>
<blockquote><strong>Note:</strong> This step is optional as your clone will do this automatically. The difference, however, is that the clone will create a remote called &#8216;origin&#8217; by default where you can name it whatever you want (sharedproject in the example) if you do run it.</blockquote>
</li>
<li>Now you can pull the code at any time with the following command.
<pre>
bash$ git pull sharedproject master
</pre>
You won&#8217;t need to do that at this point as your code is fresh from the clone, however, should you make any changes on the originating computer that have been pushed, you could now pull those changes from this secondary computer.
</ul>
</ol>

<p>If you now make changes to the code on the second computer, you can use the exact same command you used on the first computer to push the changes. First commit the changes with:
<pre>
bash$ git commit -a -m "Commit message"
</pre>
Then simply push the changes to the cloned repository with:
<pre>
bash$ git push sharedproject master
</pre></p>

<p>And now you&#8217;re up to date. The changes are ready to be downloaded from the first computer.</p>

<h2>The Urge To Merge</h2>

<p>Nothing like sexual inuendo (urge to merge, hint hint, wink wink) on a site called &#8216;Cocoa is my Girlfriend&#8217; to get a geek going, but that&#8217;s not what I mean. Settle down. Take it easy&#8230;</p>

<p>In the end, Git&#8217;s greatest feature is its ability to merge code changes.</p>

<p>There are times when you have fairly complex code merges that are necessary and systems such as CVS or SVN (Subversion) will simply choke and give up leaving the messy merging process to your weak manual merging skills. This is a shame and not necessary any more as it is rare for Git to be unable to successfully merge code. Again, this probably its biggest strength. When you don&#8217;t have to worry about merging your code, you can do whatever you like in your branch with little fear that merging in your changes are going to conflict with someone else&#8217;s. This merging power comes from Git&#8217;s unique philosophy of source code management which sees changes as individual code additions and deletions rather than complete file changes.</p>

<h2>Conclusion</h2>

<p>There will remain naysayers who have &#8220;always done it this way&#8221; and will remain in the realm of central repositories for version control. However, if you can think outside of tradition and see the power that comes from a good source control system, you will become a better programmer. I will submit that simply starting to use any version control when you haven&#8217;t before will make you a better programmer, however, using Git for your version control system, will make it infinitely easier to become so.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/06/03/version-control-makes-you-a-better-programmer/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Coding Practice: Cleaning up the default Core Data project</title>
		<link>http://www.cimgf.com/2008/05/29/coding-practice-cleaning-up-the-default-core-data-project/</link>
		<comments>http://www.cimgf.com/2008/05/29/coding-practice-cleaning-up-the-default-core-data-project/#comments</comments>
		<pubDate>Thu, 29 May 2008 18:01:52 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Coding Practice]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=133</guid>
		<description><![CDATA[In this entry I am going to do something a little different. Instead of showing some wicked code, I am going to reformat one of Apple&#8217;s default templates. Apple writes some amazing code. Unfortunately a lot of their templates demonstrate simply terrible coding practices. What is worse, people take these templates and assume that they [...]]]></description>
			<content:encoded><![CDATA[<p>In this entry I am going to do something a little different.  Instead of showing some wicked code, I am going to reformat one of Apple&#8217;s default templates.  </p>

<p>Apple writes some amazing code.  Unfortunately a lot of their templates demonstrate simply terrible coding practices.  What is worse, people take these templates and assume that they are the proper practice for coding in Objective-C and propagate that poor code into their own projects.</p>

<p>The first example I am going to tackle is the AppDelegate class that is auto generated in the Core Data template.  This is not the Core Data Document template but the standard application template.  </p>

<p><span id="more-133"></span></p>

<h3>persistentStoreCoordinator</h3>

<p>This method is not the worst in the list but will help us get into the flow of things.  The original method:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSPersistentStoreCoordinator</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> persistentStoreCoordinator <span style="color: #002200;">&#123;</span>
&nbsp;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>persistentStoreCoordinator <span style="color: #002200;">!=</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #a61390;">return</span> persistentStoreCoordinator;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #400080;">NSFileManager</span> <span style="color: #002200;">*</span>fileManager;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>applicationSupportFolder <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
    <span style="color: #400080;">NSURL</span> <span style="color: #002200;">*</span>url;
    <span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error;
&nbsp;
    fileManager <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSFileManager</span> defaultManager<span style="color: #002200;">&#93;</span>;
    applicationSupportFolder <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self applicationSupportFolder<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span> <span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>fileManager fileExistsAtPath<span style="color: #002200;">:</span>applicationSupportFolder isDirectory<span style="color: #002200;">:</span><span style="color: #a61390;">NULL</span><span style="color: #002200;">&#93;</span> <span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span>fileManager createDirectoryAtPath<span style="color: #002200;">:</span>applicationSupportFolder attributes<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    url <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURL</span> fileURLWithPath<span style="color: #002200;">:</span> <span style="color: #002200;">&#91;</span>applicationSupportFolder stringByAppendingPathComponent<span style="color: #002200;">:</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;CD_Cleanup.xml&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    persistentStoreCoordinator <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSPersistentStoreCoordinator</span> alloc<span style="color: #002200;">&#93;</span> initWithManagedObjectModel<span style="color: #002200;">:</span> <span style="color: #002200;">&#91;</span>self managedObjectModel<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>persistentStoreCoordinator addPersistentStoreWithType<span style="color: #002200;">:</span>NSXMLStoreType configuration<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> URL<span style="color: #002200;">:</span>url options<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> error<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#123;</span>
        <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSApplication</span> sharedApplication<span style="color: #002200;">&#93;</span> presentError<span style="color: #002200;">:</span>error<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>    
&nbsp;
    <span style="color: #a61390;">return</span> persistentStoreCoordinator;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>Could be worse.  There is a lot of wasted whitespace in the method itself but the majority of the problems are error checking.  Here is the cleaned up method.</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSPersistentStoreCoordinator</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>persistentStoreCoordinator
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>persistentStoreCoordinator<span style="color: #002200;">&#41;</span> <span style="color: #a61390;">return</span> persistentStoreCoordinator;
  <span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
&nbsp;
  <span style="color: #400080;">NSManagedObjectModel</span> <span style="color: #002200;">*</span>mom <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self managedObjectModel<span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>mom<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    NSAssert<span style="color: #002200;">&#40;</span><span style="color: #a61390;">NO</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;NSManagedObjectModel is nil&quot;</span><span style="color: #002200;">&#41;</span>;
    NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@:%s No model to generate a store from&quot;</span>, <span style="color: #002200;">&#91;</span>self class<span style="color: #002200;">&#93;</span>, _cmd<span style="color: #002200;">&#41;</span>;
    <span style="color: #a61390;">return</span> <span style="color: #a61390;">nil</span>;
  <span style="color: #002200;">&#125;</span>
&nbsp;
  <span style="color: #400080;">NSFileManager</span> <span style="color: #002200;">*</span>fileManager <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSFileManager</span> defaultManager<span style="color: #002200;">&#93;</span>;
  <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>applicationSupportFolder <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self applicationSupportFolder<span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span> <span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>fileManager fileExistsAtPath<span style="color: #002200;">:</span>applicationSupportFolder isDirectory<span style="color: #002200;">:</span><span style="color: #a61390;">NULL</span><span style="color: #002200;">&#93;</span> <span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>fileManager createDirectoryAtPath<span style="color: #002200;">:</span>applicationSupportFolder attributes<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
      NSAssert<span style="color: #002200;">&#40;</span><span style="color: #a61390;">NO</span>, <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> stringWithFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Failed to create App Support directory %@&quot;</span>, applicationSupportFolder<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>;
      NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Failed to create application directory: %@&quot;</span>, applicationSupportFolder<span style="color: #002200;">&#41;</span>;
      <span style="color: #a61390;">return</span> <span style="color: #a61390;">nil</span>;
    <span style="color: #002200;">&#125;</span>
  <span style="color: #002200;">&#125;</span>
&nbsp;
  <span style="color: #400080;">NSURL</span> <span style="color: #002200;">*</span>url <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURL</span> fileURLWithPath<span style="color: #002200;">:</span> <span style="color: #002200;">&#91;</span>applicationSupportFolder stringByAppendingPathComponent<span style="color: #002200;">:</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;CD_Cleanup.xml&quot;</span><span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  persistentStoreCoordinator <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSPersistentStoreCoordinator</span> alloc<span style="color: #002200;">&#93;</span> initWithManagedObjectModel<span style="color: #002200;">:</span>mom<span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>persistentStoreCoordinator addPersistentStoreWithType<span style="color: #002200;">:</span>NSXMLStoreType 
                                                configuration<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> 
                                                          URL<span style="color: #002200;">:</span>url 
                                                      options<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> 
                                                        error<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSApplication</span> sharedApplication<span style="color: #002200;">&#93;</span> presentError<span style="color: #002200;">:</span>error<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>persistentStoreCoordinator release<span style="color: #002200;">&#93;</span>, persistentStoreCoordinator <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
    <span style="color: #a61390;">return</span> <span style="color: #a61390;">nil</span>;
  <span style="color: #002200;">&#125;</span>    
&nbsp;
  <span style="color: #a61390;">return</span> persistentStoreCoordinator;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>The first change I made is in the conditional check for nil on the persistentStoreCoordinator.  This can be cleaned up to make it a simple one line of code rather than three.  It is a waste of whitespace and makes the line look far more complicated than it is.  Its simple, make it look simple.</p>

<p>Next I changed the order of things by getting a reference to the NSManagedObjectModel first.  If the model is nil then the rest is a waste of time.  Log the error and assert it as this is a show stopper in every core data application that I can think of.</p>

<p>When building the application support folder, check to make sure it succeeds!  The original code just assumes that the directory creation will work.  If it doesn&#8217;t for whatever reason is a failure and stops everything coming after it.</p>

<p>At this point you might wonder why I have both an assertion and a log statement.  I do this because I turn off assertions in the production code.  I would rather have a softer failure in production than a hard crash.  However in Development I want the code to slap me in the face when something goes wrong.</p>

<p>The last change is if there is an issue with adding the store to the coordinator.  In this case the error is presented to the user but I added a release to the coordinator.  If this doesn&#8217;t happen, any re-entrant to this method is going to be in for a nasty surprise when they get back an empty coordinator!</p>

<p>Last piece of advice on this code.  If you release an object, set its pointer to nil!  You released it, your done with it.  Why have it hang around and potentially crash your code.  Point to nil and let the failure of accessing it later be much softer.</p>

<h3>managedObjectContext</h3>

<p>Next up on the block is the context generation code itself.  This one is also not that bad other than some back-ass-wards logic statements and no error handling.  First the original code:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span> managedObjectContext <span style="color: #002200;">&#123;</span>
&nbsp;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>managedObjectContext <span style="color: #002200;">!=</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #a61390;">return</span> managedObjectContext;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #400080;">NSPersistentStoreCoordinator</span> <span style="color: #002200;">*</span>coordinator <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self persistentStoreCoordinator<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>coordinator <span style="color: #002200;">!=</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        managedObjectContext <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSManagedObjectContext</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
        <span style="color: #002200;">&#91;</span>managedObjectContext setPersistentStoreCoordinator<span style="color: #002200;">:</span> coordinator<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #a61390;">return</span> managedObjectContext;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>And the revised code:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSManagedObjectContext</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>managedObjectContext
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>managedObjectContext<span style="color: #002200;">&#41;</span> <span style="color: #a61390;">return</span> managedObjectContext;
&nbsp;
  <span style="color: #400080;">NSPersistentStoreCoordinator</span> <span style="color: #002200;">*</span>coordinator <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self persistentStoreCoordinator<span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>coordinator<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #400080;">NSMutableDictionary</span> <span style="color: #002200;">*</span>dict <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMutableDictionary</span> dictionary<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>dict setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Failed to initialize the store&quot;</span> forKey<span style="color: #002200;">:</span>NSLocalizedDescriptionKey<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>dict setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;There was an error building up the data file.  Please contact support.&quot;</span> forKey<span style="color: #002200;">:</span>NSLocalizedFailureReasonErrorKey<span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSError</span> errorWithDomain<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Zarra&quot;</span> code<span style="color: #002200;">:</span><span style="color: #2400d9;">8001</span> userInfo<span style="color: #002200;">:</span>dict<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSApplication</span> sharedApplication<span style="color: #002200;">&#93;</span> presentError<span style="color: #002200;">:</span>error<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">return</span> <span style="color: #a61390;">nil</span>;
  <span style="color: #002200;">&#125;</span>
  managedObjectContext <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSManagedObjectContext</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>managedObjectContext setPersistentStoreCoordinator<span style="color: #002200;">:</span> coordinator<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #a61390;">return</span> managedObjectContext;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>The first thing I did (and always do) is reverse and clean up the conditionals.  Putting the happy path inside of the conditional is just dumb.  Makes the code damn hard to read and maintainability goes out the window also.</p>

<p>The other change was to present an error to the user if something went wrong.  This is the single point that every other piece of code has to touch to use Core Data so it makes sense to present the error here.  As discussed in other articles, I am using an NSError to scream about the failure and then return a nil.</p>

<h3>applicationShouldTerminate:</h3>

<p>Here is the last one I will touch on today and I have definitely saved the worst for last!</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>NSApplicationTerminateReply<span style="color: #002200;">&#41;</span>applicationShouldTerminate<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSApplication</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>sender <span style="color: #002200;">&#123;</span>
&nbsp;
    <span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error;
    <span style="color: #a61390;">int</span> reply <span style="color: #002200;">=</span> NSTerminateNow;
&nbsp;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>managedObjectContext <span style="color: #002200;">!=</span> <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
        <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>managedObjectContext commitEditing<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
            <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>managedObjectContext hasChanges<span style="color: #002200;">&#93;</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>managedObjectContext save<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
&nbsp;
                <span style="color: #11740a; font-style: italic;">// This error handling simply presents error information in a panel with an </span>
                <span style="color: #11740a; font-style: italic;">// &quot;Ok&quot; button, which does not include any attempt at error recovery (meaning, </span>
                <span style="color: #11740a; font-style: italic;">// attempting to fix the error.)  As a result, this implementation will </span>
                <span style="color: #11740a; font-style: italic;">// present the information to the user and then follow up with a panel asking </span>
                <span style="color: #11740a; font-style: italic;">// if the user wishes to &quot;Quit Anyway&quot;, without saving the changes.</span>
&nbsp;
                <span style="color: #11740a; font-style: italic;">// Typically, this process should be altered to include application-specific </span>
                <span style="color: #11740a; font-style: italic;">// recovery steps.  </span>
&nbsp;
                <span style="color: #a61390;">BOOL</span> errorResult <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSApplication</span> sharedApplication<span style="color: #002200;">&#93;</span> presentError<span style="color: #002200;">:</span>error<span style="color: #002200;">&#93;</span>;
&nbsp;
                <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>errorResult <span style="color: #002200;">==</span> <span style="color: #a61390;">YES</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
                    reply <span style="color: #002200;">=</span> NSTerminateCancel;
                <span style="color: #002200;">&#125;</span> 
&nbsp;
                <span style="color: #a61390;">else</span> <span style="color: #002200;">&#123;</span>
&nbsp;
                    <span style="color: #a61390;">int</span> alertReturn <span style="color: #002200;">=</span> NSRunAlertPanel<span style="color: #002200;">&#40;</span><span style="color: #a61390;">nil</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Could not save changes while quitting. Quit anyway?&quot;</span> , <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Quit anyway&quot;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Cancel&quot;</span>, <span style="color: #a61390;">nil</span><span style="color: #002200;">&#41;</span>;
                    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>alertReturn <span style="color: #002200;">==</span> NSAlertAlternateReturn<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
                        reply <span style="color: #002200;">=</span> NSTerminateCancel;	
                    <span style="color: #002200;">&#125;</span>
                <span style="color: #002200;">&#125;</span>
            <span style="color: #002200;">&#125;</span>
        <span style="color: #002200;">&#125;</span> 
&nbsp;
        <span style="color: #a61390;">else</span> <span style="color: #002200;">&#123;</span>
            reply <span style="color: #002200;">=</span> NSTerminateCancel;
        <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #a61390;">return</span> reply;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>This one just makes me want to cry.  Follow that happy path, go ahead, I&#8217;ll wait.</p>

<p>Not very clean cut is it?  It goes in and out of several conditions, else statements, an error and finally an alert panel.  Code like this makes people think that Objective-C is hard!  Try this version instead:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>NSApplicationTerminateReply<span style="color: #002200;">&#41;</span>applicationShouldTerminate<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSApplication</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>sender
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>managedObjectContext<span style="color: #002200;">&#41;</span> <span style="color: #a61390;">return</span> NSTerminateNow;
&nbsp;
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>managedObjectContext commitEditing<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@:%s unable to commit editing to terminate&quot;</span>, <span style="color: #002200;">&#91;</span>self class<span style="color: #002200;">&#93;</span>, _cmd<span style="color: #002200;">&#41;</span>;
    <span style="color: #a61390;">return</span> NSTerminateCancel;
  <span style="color: #002200;">&#125;</span>
&nbsp;
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>managedObjectContext hasChanges<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #a61390;">return</span> NSTerminateNow;
&nbsp;
  <span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span><span style="color: #002200;">&#91;</span>managedObjectContext save<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">BOOL</span> result <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>sender presentError<span style="color: #002200;">:</span>error<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>result<span style="color: #002200;">&#41;</span> <span style="color: #a61390;">return</span> NSTerminateCancel;
&nbsp;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>question <span style="color: #002200;">=</span> NSLocalizedString<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Could not save changes while quitting.  Quit anyway?&quot;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Quit without saves error question message&quot;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>info <span style="color: #002200;">=</span> NSLocalizedString<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Quitting now will lose any changes you have made since the last successful save&quot;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Quit without saves error question info&quot;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>quitButton <span style="color: #002200;">=</span> NSLocalizedString<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Quit anyway&quot;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Quit anyway button title&quot;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>cancelButton <span style="color: #002200;">=</span> NSLocalizedString<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Cancel&quot;</span>, <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Cancel button title&quot;</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #400080;">NSAlert</span> <span style="color: #002200;">*</span>alert <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSAlert</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>alert setMessageText<span style="color: #002200;">:</span>question<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>alert setInformativeText<span style="color: #002200;">:</span>info<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>alert addButtonWithTitle<span style="color: #002200;">:</span>quitButton<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>alert addButtonWithTitle<span style="color: #002200;">:</span>cancelButton<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #a61390;">int</span> answer <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>alert runModal<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>alert release<span style="color: #002200;">&#93;</span>, alert <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>answer <span style="color: #002200;">==</span> NSAlertAlternateReturn<span style="color: #002200;">&#41;</span> <span style="color: #a61390;">return</span> NSTerminateCancel;
&nbsp;
  <span style="color: #002200;">&#125;</span>
&nbsp;
  <span style="color: #a61390;">return</span> NSTerminateNow;
<span style="color: #002200;">&#125;</span></pre></div></div>


<p>In this revised method, all of the logic is reversed.  The happy path is now along the left edge of the method and much easier to follow.  First, if there is no context, terminate now.  If we cannot commit any active editing, give up.  If there are no changes, terminate now.  All of those are now extremely easy to follow and the bulk of the situations are taken care of.  This leaves us with only one issue remaining, an actual honest failure.</p>

<p>When we try to save we look at the result.  If there is a failure in the save we present it to the application that is passed (why not, its there!) to the method.  After that we give the user a choice, just like in the original method to quit anyway or abort the application termination.  You might notice that my alert message is a lot more code than the original.  That is for two reasons.  First I do not like to use the C calls and second, my message is <strong>localized</strong>.  Always, always, always localize any strings that are going to be presented to the user.  Even if the application will never, ever be localized, do it anyway.  You will thank me down the road when that never ever turns into now!</p>

<h3>Conclusion</h3>

<p>Now I doubt that Apple is using code like this themselves.  It is clearly quick and dirty code that they put together and never went back to revisit it.  I get that and totally understand.  However <strong>WE</strong> should never use code like this in our applications.  It is asking for trouble and people will laugh at us when they see it.</p>

<p>There is a taste of my coding style.  I like the happy path to be on the left; I think the &#8220;single return&#8221; mythology is a bunch of crap and you should failure early and return often.</p>

<p>Comments?  I would love to hear them.  If you are going to comment on the multiple returns, don&#8217;t bother, you will be ignored.</p>

<p>Per bbum&#8217;s suggestion this new code is filed under radar #5972712</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/05/29/coding-practice-cleaning-up-the-default-core-data-project/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Cocoa Tutorial: Wiring Undo Management Into Core Data</title>
		<link>http://www.cimgf.com/2008/04/30/cocoa-tutorial-wiring-undo-management-into-core-data/</link>
		<comments>http://www.cimgf.com/2008/04/30/cocoa-tutorial-wiring-undo-management-into-core-data/#comments</comments>
		<pubDate>Wed, 30 Apr 2008 17:46:55 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Core Data]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=115</guid>
		<description><![CDATA[Undo support in Cocoa is fantastic but for those who have tried to mix it with Core Data know that it can be a bit frustrating. Generally, undo support can be ignored in most applications and it will &#8220;just work&#8221;. But when Core Data is added to the recipe then things get a bit confusing [...]]]></description>
			<content:encoded><![CDATA[<p>Undo support in Cocoa is fantastic but for those who have tried to mix it with Core Data know that it can be a bit frustrating.  Generally, undo support can be ignored in most applications and it will &#8220;just work&#8221;.  But when Core Data is added to the recipe then things get a bit confusing and more complicated.</p>

<p><span id="more-115"></span></p>

<h3>The Conflict With NSUndoManager</h3>

<p>For those familiar with the inner workings of Cocoa&#8217;s undo support (and if you are not familiar with it, check out the <a href="http://www.mactech.com/articles/mactech-synopses/304900-24.04-Grokking-Synopsis.html">April edition of MacTech ;-) </a>, all of the undo events are registered with an NSUndoManager.  In a normal document model application, the window controller (or the window&#8217;s delegate if set to something other than the controller) will supply an NSUndoManager for all of the text fields and other editable bits in the window.  </p>

<p>This works fine until Core Data comes along.  The reason for this is that the NSManagedObjectContext has its own NSUndoManager that is registering those same events and can easily get out of sync.  </p>

<p>What I prefer to do is avoid the double NSUndoManager and just use the one included with the NSManagedObjectContext.  This can be done by implementing one of the window delegate methods:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSUndoManager</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>windowWillReturnUndoManager<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSWindow</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>window
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>self undoManager<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #400080;">NSUndoManager</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>undoManager
<span style="color: #002200;">&#123;</span>
  <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self managedObjectContext<span style="color: #002200;">&#93;</span> undoManager<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>By utilizing the NSUndoManager that is included in the context, some very powerful features are enabled.</p>

<h3>Grouping sheet modifications</h3>

<p>A common UI design is to allow the editing of an object in a sheet.  The user double clicks on the item or otherwise indicates that they want to edit it and a sheet drops down allowing them to change the values.  Naturally, that sheet has an NSUndoManager attached to it (can even use the one from Core Data) and each individual field can be undone.  However, how to do we handle the cancel button or the ability to undo the entire sheet?</p>

<p>Both of the above can be handled with groupings inside of the NSManagedObjectContext object&#8217;s NSUndoManager.  The methods would work as follows:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>presentEditSheet<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self undoManager<span style="color: #002200;">&#93;</span> beginUndoGrouping<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>NSApp beginSheet<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self editSheet<span style="color: #002200;">&#93;</span> 
     modalForWindow<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self window<span style="color: #002200;">&#93;</span> 
      modalDelegate<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> 
     didEndSelector<span style="color: #002200;">:</span><span style="color: #a61390;">NULL</span> 
        contextInfo<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>acceptChanges<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self editSheet<span style="color: #002200;">&#93;</span> orderOut<span style="color: #002200;">:</span>sender<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>NSApp endSheet<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self editSheet<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self undoManager<span style="color: #002200;">&#93;</span> endUndoGrouping<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self undoManager<span style="color: #002200;">&#93;</span> setActionName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Object edit&quot;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>cancelChanges<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender
<span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self editSheet<span style="color: #002200;">&#93;</span> orderOut<span style="color: #002200;">:</span>sender<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span>NSApp endSheet<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self editSheet<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self undoManager<span style="color: #002200;">&#93;</span> endUndoGrouping<span style="color: #002200;">&#93;</span>;
  <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self undoManager<span style="color: #002200;">&#93;</span> undo<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>In this example I have started an undo group before presenting the sheet.  After the sheet is closed I then end the grouping and if the sheet was not cancelled I give the group a name.  This name will display in the menu and allow all of the changes inside of the sheet to be undone in one stroke.  If the sheet is cancelled then the group is still closed but I immediately call undo instead and everything that occurred within the sheet is wiped clean.</p>

<h3>Conclusion</h3>

<p>By only using one NSUndoManager it makes life a lot simplier and gives consistent results to the user.  This technique can also be used in a document model application but each document will have to reference the appropriate NSUndoManager that is associated with its own NSManagedObjectContext.</p>

<h3>Feedback</h3>

<p>If you have some other interesting ways to use the NSUndoManager I would love to hear about them either here in the comments or you can email me directly at marcus at cimgf.com.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/04/30/cocoa-tutorial-wiring-undo-management-into-core-data/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Cocoa Tutorial: Don&#8217;t Be Lazy With NSDecimalNumber (Like Me)</title>
		<link>http://www.cimgf.com/2008/04/23/cocoa-tutorial-dont-be-lazy-with-nsdecimalnumber-like-me/</link>
		<comments>http://www.cimgf.com/2008/04/23/cocoa-tutorial-dont-be-lazy-with-nsdecimalnumber-like-me/#comments</comments>
		<pubDate>Wed, 23 Apr 2008 16:42:58 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=106</guid>
		<description><![CDATA[NSDecimalNumber is Objective-Câ€™s solution to numbers that need to be very precise. The documentation defines it as: NSDecimalNumber, an immutable subclass of NSNumber, provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits [...]]]></description>
			<content:encoded><![CDATA[<p>NSDecimalNumber is Objective-Câ€™s solution to numbers that need to be very precise. The documentation defines it as:</p>

<blockquote>NSDecimalNumber, an immutable subclass of NSNumber, provides an object-oriented wrapper for doing base-10 arithmetic. An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer up to 38 digits long, and exponent is an integer from â€“128 through 127.</blockquote>

<h2>NSDecimalNumber</h2>

<p>If you are dealing with currency at all, then you should be using NSDecimalNumber. However, since it is immutable and definitely not a primitive then it is difficult to use right? Well â€” yes â€” a bit. But if you do not want to see your $9.50 item displayed as $9.49999994 or something then you are better off using NSDecimalNumber right from the beginning. Otherwise you are going to be converting to it later and that is a LOT more painful.</p>

<p><span id="more-106"></span></p>

<p>To create an NSDecimalNumber there are a few helper class methods:</p>

<ul>
    <li>+decimalNumberWithDecimal:â€¨</li>
    <li>+decimalNumberWithMantissa:exponent:isNegative:â€¨</li>
    <li>+decimalNumberWithString:â€¨</li>
    <li>+deicmalNumberWithString:locale:â€¨</li>
    <li>+oneâ€¨</li>
    <li>+zeroâ€¨</li>
    <li>+notANumber</li>
</ul>

<p>The two methods that I ended up using the most are +decimalNumberWithDecimal: and +decimalNumberWithMantissa:exponent:isNegative: If you already have the number stored as an NSNumber then
[NSDecimalNumber decimalNumberWithDecima:[yourNumber decimalValue]]
is the easiest way to convert it. If the number is a primitive then
[NSDecimalNumber decimalNumberWithMantissa:(yourPrimitive * precision) exponent:-(precision) isNegative:(yourPrimitive < 0 ? YES : NO)] will convert it.</p>

<h2>Math functions</h2>

<p>So now you have your number as an NSDecimalNumber. How do you do anything with it? Specifically how do you add, divide, multiple and subtract an immutable number? Fortunately the class has methods to handle all of these:</p>

<ul>
<li>-decimalNumberByAdding:â€¨</li>
<li>-decimalNumberBySubtracting:â€¨</li>
<li>-decimalNumberByMultiplingBy:â€¨</li>
<li>-decimalNumberByDividingBy:â€¨</li>
<li>-decimalNumberByRaisingToPower:â€¨</li>
<li>-decimalNumberByMultiplyingByPowerOf10:</li>
</ul>

<p>With these methods you can do all of the math functions and create a new NSDecimalNumber with each call. Naturally these can even be chained together to make a deliciously convoluted method call.</p>

<h2>Rounding</h2>

<p>So what happens when you need to control the decimal precision of an NSDecimalNumber? Specifically what happens when you multiply 9.49 * 10% and what only two decimal points left over? That is where the NSDecimalNumberBehaviors come in. The NSDecimalNumberBehaviors protocol is defined as:</p>

<p>The NSDecimalBehaviors protocol declares three methods that control the discretionary aspects of working with NSDecimalNumber objects.</p>

<p>The scale and roundingMode methods determine the precision of NSDecimalNumberâ€™s return values and the way in which those values should be rounded to fit that precision. The exceptionDuringOperation:error:leftOperand:rightOperand: method determines the way in which an NSDecimalNumber object should handle different calculation errors.</p>

<p>For an example of a class that adopts the NSDecimalBehaviors protocol, see the specification for NSDecimalNumberHandler.</p>

<p>This protocol is implemented in the NSDecimalNumberHandler class. By constructing an NSDecimalNumberHandler and passing it in as part of the math call you can control the rounding applied to the math function. Even better, you can reuse the handler class as often as you want. Therefore to perform the calculation above:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSDecimalNumber</span> <span style="color: #002200;">*</span>price <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSDecimalNumber</span> decimalNumberWithMantissa<span style="color: #002200;">:</span><span style="color: #2400d9;">949</span>
                                                           exponent<span style="color: #002200;">:-</span><span style="color: #2400d9;">2</span>
                                                         isNegative<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;â€¨
<span style="color: #400080;">NSDecimalNumber</span> <span style="color: #002200;">*</span>percent <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSDecimalNumber</span> decimalNumberWithMatissa<span style="color: #002200;">:</span><span style="color: #2400d9;">10</span>
                                                            exponent<span style="color: #002200;">:-</span><span style="color: #2400d9;">2</span>
                                                          isNegative<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;â€¨
<span style="color: #400080;">NSDecimalNumberHandler</span> <span style="color: #002200;">*</span>handler <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSDecimalNumberHandler</span> decimalNumberHandlerWithRoundingMode<span style="color: #002200;">:</span>NSRoundPlain
                                                                                         scale<span style="color: #002200;">:-</span><span style="color: #2400d9;">2</span>
                                                                              raiseOnExactness<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span>
                                                                               raiseOnOverflow<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span>
                                                                              raiseOnUnderflow<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span>
                                                                           raiseOnDivideByZero<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
<span style="color: #400080;">NSDecimalNumber</span> <span style="color: #002200;">*</span>result <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>price decimalNumberByMultiplyingBy<span style="color: #002200;">:</span>percent
                                                 withBehavior<span style="color: #002200;">:</span>handler<span style="color: #002200;">&#93;</span>;</pre></div></div>


<p>Note that instead of using -decimalNumberByMultiplyingBy: I used a similar method which adds withBehavior: on the end of it. Each of the math functions listed above includes a companion method which allows you to pass in the behavior. Also note that the NSDecimalNumberHandler class allows you to raise exceptions in several circumstances. You can review Appleâ€™s documentation on each of these exceptions if you find a need for them.</p>

<h2>Core Data</h2>

<p>So how does Core Data handle NSDecimalNumber(s)? In a word â€” perfectly. In your Core Data model simply define the attribute as â€œdecimalâ€ instead of double or another primitive and you can store the NSDecimalNumber directly in the repository and retrieve it as an NSDecimalNumber. You can also retrieve it as an NSNumber if needed since NSDecimalNumber is a subclass of NSNumber.</p>

<h2>Formatting</h2>

<p>All of the number formatters will handle NSDecimalNumber perfectly with no loss of precision. If you pass it to a currency formatter you will get back the number you expect unlike passing a double and hoping for the best.</p>

<h2>Conclusion</h2>

<p>So is NSDecimalNumber harder to use than primitives? Absolutely. Compared to primitives it is a lot harder to code, maintain and read. Is it worth it? Depends.</p>

<p>If you are dealing with currency then there is no question â€” use NSDecimalNumber and avoid doubles like the plague. Spend the time, learn the API. Otherwise you will end up having to migrate over to them later when you discover that $9.49 * 10% may not equal $0.95.</p>

<p>If you are not dealing with currency or another number that requires absolute precision (such as screen drawing, et al) then you probably do not need to deal with the pain.</p>

<p>So why did I title this article with the words â€œLike Meâ€? Take a good guessâ€¦</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/04/23/cocoa-tutorial-dont-be-lazy-with-nsdecimalnumber-like-me/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Git and XCode: A git build number script</title>
		<link>http://www.cimgf.com/2008/04/13/git-and-xcode-a-git-build-number-script/</link>
		<comments>http://www.cimgf.com/2008/04/13/git-and-xcode-a-git-build-number-script/#comments</comments>
		<pubDate>Mon, 14 Apr 2008 01:36:48 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Development Environment]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[Version Control]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=95</guid>
		<description><![CDATA[Git has been gaining in popularity with Cocoa developers as well as open source developers. As I work it into my development workflow, one item that was missing was the automatic injection of the build number into the application bundle. There are a few scripts floating around that perform this trick for subversion, but git [...]]]></description>
			<content:encoded><![CDATA[<p>Git has been gaining in popularity with Cocoa developers as well as open source developers.  As I work it into my development workflow, one item that was missing was the automatic injection of the build number into the application bundle.</p>

<p>There are a few scripts floating around that perform this trick for subversion, but git handles build numbers a bit differently and it appears that no one has bothered to publish one.  As is known, subversion uses an incrementing integer for build numbers.  This makes it very easy to determine which build number came first and makes it very useful for a non-public version number.  Git, however, uses a hash for each build number which is not incrementing and therefore not very useful for determining version numbers.  However, it is still very useful for pulling up a specific build when a crash report is received, etc.</p>

<p>Therefore, with the help of Matt Long&#8217;s perl-fu, I have updated Daniel Jalkut&#8217;s subversion perl script to work with git.  Since the build numbers are not sequential, I would not recommend using them for Sparkle.  Therefore, in my own build process for iWeb Buddy, I hand select the version number (for example 1.0.4) and then use the short hash from git as the CFBundleVersion number.  Normally this number is displayed in parens after the primary build number but, at least in iWeb Buddy, I have removed it from the display entirely.  Since it is no longer a sequential number it would only potentially confuse users and it displays in the crash reports anyway.</p>

<p>The updated script is as follows:</p>


<div class="wp_syntax"><div class="code"><pre class="perl" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># Xcode auto-versioning script for Subversion by Axel Andersson</span>
<span style="color: #666666; font-style: italic;"># Updated for git by Marcus S. Zarra and Matt Long</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">use</span> strict<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># Get the current git commit hash and use it to set the CFBundleVersion value</span>
<span style="color: #b1b100;">my</span> <span style="color: #0000ff;">$REV</span> <span style="color: #339933;">=</span> <span style="color: #ff0000;">`/opt/local/bin/git show --abbrev-commit | grep &quot;^commit&quot;`</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">my</span> <span style="color: #0000ff;">$INFO</span> <span style="color: #339933;">=</span> <span style="color: #ff0000;">&quot;$ENV{BUILT_PRODUCTS_DIR}/$ENV{WRAPPER_NAME}/Contents/Info.plist&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">my</span> <span style="color: #0000ff;">$version</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">$REV</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">$version</span> <span style="color: #339933;">=~</span> <span style="color: #009966; font-style: italic;">/^commit\s+([^.]+)\.\.\.$/</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span> 
	<span style="color: #0000ff;">$version</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">$1</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #b1b100;">else</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #0000ff;">$version</span> <span style="color: #339933;">=</span> <span style="color: #000066;">undef</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000066;">die</span> <span style="color: #ff0000;">&quot;$0: No Git revision found&quot;</span> <span style="color: #b1b100;">unless</span> <span style="color: #0000ff;">$version</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066;">open</span><span style="color: #009900;">&#40;</span>FH<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;$INFO&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">or</span> <span style="color: #000066;">die</span> <span style="color: #ff0000;">&quot;$0: $INFO: $!&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">my</span> <span style="color: #0000ff;">$info</span> <span style="color: #339933;">=</span> <span style="color: #000066;">join</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;&quot;</span><span style="color: #339933;">,</span> <span style="color: #009999;">&lt;FH&gt;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066;">close</span><span style="color: #009900;">&#40;</span>FH<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #0000ff;">$info</span> <span style="color: #339933;">=~</span> <span style="color: #009966; font-style: italic;">s/([\t ]+&lt;key&gt;CFBundleVersion&lt;\/key&gt;\n[\t ]+&lt;string&gt;).*?(&lt;\/string&gt;)/$1$version$2/</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066;">open</span><span style="color: #009900;">&#40;</span>FH<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;&gt;$INFO&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">or</span> <span style="color: #000066;">die</span> <span style="color: #ff0000;">&quot;$0: $INFO: $!&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000066;">print</span> FH <span style="color: #0000ff;">$info</span><span style="color: #339933;">;</span>
<span style="color: #000066;">close</span><span style="color: #009900;">&#40;</span>FH<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>


<p>Since git is distributed, there is no need to be online to produce a build.  The script will grab the current abbrev-commit hash and will inject it into the current build&#8217;s Info.plist file.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/04/13/git-and-xcode-a-git-build-number-script/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Cocoa Tutorial: Using NSError to Great Effect</title>
		<link>http://www.cimgf.com/2008/04/04/cocoa-tutorial-using-nserror-to-great-effect/</link>
		<comments>http://www.cimgf.com/2008/04/04/cocoa-tutorial-using-nserror-to-great-effect/#comments</comments>
		<pubDate>Fri, 04 Apr 2008 19:42:00 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/?p=89</guid>
		<description><![CDATA[Error handling is rarely fun. I find myself often re-coding a method after I realize that I need to handle one error condition or another. Usually, error handling involves either try/catch or some return code strategy. Neither of those is pretty or easy to maintain. For Objective-C development, however, there is another option &#8212; NSError. [...]]]></description>
			<content:encoded><![CDATA[<p>Error handling is rarely fun.  I find myself often re-coding a method after I realize that I need to handle one error condition or another.  Usually, error handling involves either try/catch or some return code strategy.  Neither of those is pretty or easy to maintain.  For Objective-C development, however, there is another option &#8212; NSError.
<span id="more-89"></span></p>

<h2>Try/Catch</h2>

<p>I truly dislike using try/catch.  It indents my code all to hell, is difficult to follow and even more difficult to debug.  Anyone who has written Java code for any length of time knows the true hell that is try/catch.  Therefore I try to avoid this method of error handling if at all possible.  I find that it interrupts the logical flow of the code and is just plain rude.</p>

<h2>Return Codes</h2>

<p>This is probably the more common method of handling errors.  Return an integer and let the calling code decide how to handle it.  This is definitely better than the try/catch solution as it does not indent the code badly and does not interrupt the logic flow.  However, I find that return codes are harder to maintain than they should be.  What was 1?  What about 2?  And 12342 was what again?!?</p>

<p>And worse, what happens when everything goes right and I need to return an object? Oops&#8230;</p>

<h2>Introduction to NSError</h2>

<p>Fortunately, there is a better solution.  <strong>NSError</strong> allows me to return whatever I want, handles errors without breaking the logic flow, and has quite a few other features.  First some code to demonstrate how Apple uses <strong>NSError</strong>:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
<span style="color: #a61390;">BOOL</span> success <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>myContext save<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span>;
<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>success<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
  <span style="color: #002200;">&#91;</span>NSApp presentError<span style="color: #002200;">:</span>error<span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">return</span>;
<span style="color: #002200;">&#125;</span>
<span style="color: #11740a; font-style: italic;">//Continue processing</span></pre></td></tr></table></div>


<p>In this simple example, I am calling save on my <strong>NSManagedObjectContext</strong> and I am passing in an <strong>NSError</strong> pointer.  If there is an issue, then that pointer will reference an <strong>NSError</strong> object that I can then utilize however I need.  In this case I am simply passing it off to the <strong>NSApp</strong> to be displayed to the user.  However, I could just as easily have done this:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>success<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
  NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@:%s Error saving context: %@&quot;</span>, <span style="color: #002200;">&#91;</span>self class<span style="color: #002200;">&#93;</span>, _cmd, <span style="color: #002200;">&#91;</span>error localizedDescription<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
  <span style="color: #a61390;">return</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>I suggest reviewing Apple&#8217;s Documentation on <a href='http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSError_Class/index.html'>NSError</a> to discover all of  the information that is available.</p>

<h2>Passing Pointers to Pointers</h2>

<p>Using the <strong>NSError</strong> class in the above example is quite simple.  I just pass it in and if the call failed for whatever reason I have an <strong>NSError</strong> object to explain what the problem was.  But how does the other side of that call work?</p>

<p>The first part of this is to understand the concept of passing a pointer to a pointer rather than a pointer to an object.  Normally when a message is sent, a pointer to the object is being passed in the message.  This is denoted with the single asterisk(*) in the method signature such as</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>appendString<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSString</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>newString</pre></div></div>


<p>This is different then passing a pointer to a pointer.  First, that type of argument is denoted with two asterisk(**) such as:</p>


<div class="wp_syntax"><div class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>save<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSError</span><span style="color: #002200;">**</span><span style="color: #002200;">&#41;</span>error</pre></div></div>


<p>Second, the other difference is this allows the receiving method to control what the pointer (that the pointer is pointing to) is referencing.  This is arguably one of the more confusing parts of pointer programming but once you get it, it is a very powerful tool.  To put it another way, by passing a pointer to the pointer, the receiving method can decide what your variable&#8217;s value is.  As you can see in my code above, I initialized the error variable to nil.  However, if the save call fails, that variable will no longer be nil but will reference an actual <strong>NSError</strong> object which I can than interrogate.</p>

<p>If you wish to understand how this works, I would suggest the <a href='http://en.wikipedia.org/wiki/Pointer_(computing)#Double_indirection'>double indirection wikipedia</a> article as a great starting point.</p>

<h2>Using NSError Handling in My Code</h2>

<p>With a firm understanding of double indirection pointers &lt;/smile&gt; I am now able to build my own methods that accept a pointer to an <strong>NSError</strong> object and I can utilize that pointer if anything goes wrong.  Consider the following code:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>fetchDocument<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSURL</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>url error<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSError</span><span style="color: #002200;">**</span><span style="color: #002200;">&#41;</span>error
<span style="color: #002200;">&#123;</span>
  <span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span>myString <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> alloc<span style="color: #002200;">&#93;</span> initWithContentsOfURL<span style="color: #002200;">:</span>url<span style="color: #002200;">&#93;</span>;
&nbsp;
  <span style="color: #11740a; font-style: italic;">//start to do something wickedly cool with the data</span>
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #11740a; font-style: italic;">//An error occurred</span>
    <span style="color: #400080;">NSMutableDictionary</span> <span style="color: #002200;">*</span>errorDetail <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSMutableDictionary</span> dictionary<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>errorDetail setValue<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Failed to do something wicked&quot;</span> forKey<span style="color: #002200;">:</span>NSLocalizedDescriptionKey<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSError</span> errorWithDomain<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;myDomain&quot;</span> code<span style="color: #002200;">:</span><span style="color: #2400d9;">100</span> userInfo<span style="color: #002200;">:</span>errorDetail<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">return</span> <span style="color: #a61390;">nil</span>;
  <span style="color: #002200;">&#125;</span>
  <span style="color: #11740a; font-style: italic;">//Finish doing something wicked</span>
  <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSObject</span> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span> autorelease<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>In this example, I have passed in an <strong>NSURL</strong>.  Using that <strong>NSURL</strong> object I have populated a string with it and the &#8220;do something wicked&#8221; with the contents of the <strong>NSString</strong>.  However, there is an error in the processing and therefore I want to notify the calling code that it failed.  To do this I first constructed an <strong>NSMutableDictionary</strong> that contains all of the information about the failure.  In this example I only populated the localized description key but I could have put a lot more in there.</p>

<p>Once the dictionary is populated, I then initialized an NSError object using the helper method that gives me back an auto-released object.  I then assigned that object back to the pointer that was passed in.  The interesting piece of code here is how I am referencing the passed in pointer.  To update the pointer that the passed in pointer is pointing to I need to include an asterisk before the name of the variable.  This tells the compiler that I want to change what the pointer to pointer is pointing to.  Yes &#8212; it is a bit confusing but the end result is that the <strong>NSError</strong> reference in the calling method will reference the <strong>NSError</strong> object that has been constructed in the called method and thus allowing me to pass information back to the calling method along a second path.</p>

<p>By utilizing an <strong>NSError</strong> in this manner, I am able to return anything I need when the method is successful and still able to send back all of the error information required when something goes wrong.</p>

<h2>Displaying NSError Objects</h2>

<p>Once you get an <strong>NSError</strong> object back from a method there are a lot of things that can be done with it.  Since Apple uses them so often in their own code, a way to present them to the User has been included in the Cocoa APIs.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>IBAction<span style="color: #002200;">&#41;</span>thrower<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender;
<span style="color: #002200;">&#123;</span>
  <span style="color: #400080;">NSError</span> <span style="color: #002200;">*</span>error <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
  <span style="color: #a61390;">id</span> result <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self fetchDocument<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSURL</span> URLWithString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;http://www.apple.com&quot;</span><span style="color: #002200;">&#93;</span> error<span style="color: #002200;">:&amp;</span>error<span style="color: #002200;">&#93;</span>;
  <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>error<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>NSApp presentError<span style="color: #002200;">:</span>error<span style="color: #002200;">&#93;</span>;
    <span style="color: #a61390;">return</span>;
  <span style="color: #002200;">&#125;</span>
  NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Result received: %@&quot;</span>, result<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>In this example, I am checking to see if the error is still nil after my message call.  If it is no longer nil I know that an error occurred and that I need to display it to the user.  Apple provides a built in method to do this with a call to <em>presentError:</em> on the <strong>NSApplication</strong> instance.  If you run the example project included you will see that this presents a dialog window to the user with the localized description displayed.</p>

<h2>Conclusion</h2>

<p>This article will be followed up with another one detailing some of the more interesting things that you can do with <strong>NSError</strong> objects.  Hopefully this taste will highlight the usefulness of this method of error handling and how it is an improvement over both try/catch blocks and return codes.</p>

<p><a href="http://www.cimgf.com/wp-content/uploads/2008/04/nserrortutorial.zip" title="NSErrorTutorial.zip"><center><img src="http://www.cimgf.com/wp-content/uploads/2008/03/xcode.png" alt="xcode.png" border="0" width="128" height="128" /><br/>Download the Example Project</center></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/04/04/cocoa-tutorial-using-nserror-to-great-effect/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Cocoa Tutorial: Fixing Memory Leaks With Instruments</title>
		<link>http://www.cimgf.com/2008/04/02/cocoa-tutorial-fixing-memory-leaks-with-instruments/</link>
		<comments>http://www.cimgf.com/2008/04/02/cocoa-tutorial-fixing-memory-leaks-with-instruments/#comments</comments>
		<pubDate>Thu, 03 Apr 2008 00:58:50 +0000</pubDate>
		<dc:creator>Matt Long</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Development Environment]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/2008/04/02/cocoa-tutorial-fixing-memory-leaks-with-instruments/</guid>
		<description><![CDATA[As I am getting toward what I think is the end of coding for an application I hope to release soon, the nitty gritty work of fixing leaks, optimizing code, and squashing bugs has become the majority of what I&#8217;m doing now. Gone is the fun part of the application development process where I was [...]]]></description>
			<content:encoded><![CDATA[<p><img src='http://www.cimgf.com/wp-content/uploads/2008/04/leaks_icon.png' alt='Leaks Icon' align='left'/>As I am getting toward what I think is the end of coding for an application I hope to release soon, the nitty gritty work of fixing leaks, optimizing code, and squashing bugs has become the majority of what I&#8217;m doing now. Gone is the fun part of the application development process where I was creating features and solving new problems. It is now drudgery and focusing requires diligence. I know that the rewards are worth it as these final steps are what give an application stability and make it shine, but getting through it can be nothing but toil. Fortunately with the developer tools that shipped with Leopard, Apple has made this work much easier to handle in a little application called Instruments.
<span id="more-78"></span></p>

<p>As usual, I&#8217;ve created a demo application that will allow you to see how things work. You can download it here: <a href='http://www.cimgf.com/wp-content/uploads/2008/04/leaky.zip' title='Leaky Demo Application'>Leaky Demo Application</a>. In this post I am simply going to show you how to use Instruments to detect memory leaks. It&#8217;s pretty straightforward, but there are few little nuances you may not be familiar with that once you understand will help you feel comfortable using this powerful tool.</p>

<h2>Running Instruments From XCode</h2>

<p>You can start Instruments directly and then navigate to your project build, however, it&#8217;s much quicker and simpler to start Instruments from XCdoe. To do so , open the demo project or a project of your own in XCode and select <strong>Run | Start With Performance Tool | Leaks</strong>.</p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2008/04/start_leaks.png' title='Start Leaks Instrument' rel='lightbox'><img src='http://www.cimgf.com/wp-content/uploads/2008/04/start_leaks.thumbnail.png' alt='Start Leaks Instrument' /></a></p>

<p>While working on this project, Marcus and I discovered a few things that you should keep in mind while you are using Instruments.</p>

<ul>
<li><strong>Breakpoints Do Not Break</strong>. Instruments utilizes debug information from your debug build, however, it does not stop at break points you set. This is because while you are loading your application into Instruments from the menu in XCode, Instruments simply uses the path of the current executable as its start path and loads it externally from XCode. The menu in XCode is really there as a convenience mechanism. This is not a big deal as you can always run again in Debug mode after your instruments session should you want your application to break. It&#8217;s just something to make a note of.</li>
<br />
<li><strong>NSLog Statements Do Not Show In The Debugger Console</strong>. If you want to see your NSLog statements, you will need to load the system Console application (<em>/Applications/Utilities/Console</em>).</li>
</ul>

<h2>Leaking Like A Sieve&#8230; Or Not</h2>

<p>Our expectation was that when we allocated memory for a new <em>NSString*</em> object we would see it leak right away. This was, after all, our intention. Things, however, don&#8217;t always work the way you might expect. This code would not leak in our tests no matter what we tried.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #400080;">NSString</span> <span style="color: #002200;">*</span><span style="color: #a61390;">string</span> <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSString</span> alloc<span style="color: #002200;">&#93;</span> initWithString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Leaker&quot;</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>


<p>And here&#8217;s why. It turns out that since <em>NSString</em>(s) are immutable and since we are allocating the string using the <strong>@</strong> operator, the compiler is making things more efficient for us. Strings with the same contents are given the same memory address. Here is a comment from the CocoaDev site that clarifies what I mean.</p>

<blockquote>
The nice thing about using the @&#8221;" notation for initializing NSString objects is that if you create two of them and their content is the same, the runtime uses the same storage for them. (Note, this is not guaranteed and certainly may not be the case across compilation unit or library boundaries. It is a performance optimization and the fact that it happens sometimes should not lead you to believe that you can safely, for example, use &#8220;==&#8221; to compare strings if you know they&#8217;re both from string constants.) <a href="http://www.cocoadev.com/index.pl?NSString">(Ref. CocoaDev NSString)</a>
</blockquote>

<p>In the example code, the NSString objects never leak and so they weren&#8217;t very useful. This isn&#8217;t to say that they never will leak, so you should be in the habit of calling <em>release</em> on your NSString(s), however, for our example project at least, the NSString leaks were never detected. We instead switched over to using NSMutableString at which point the application began to leak as desired.</p>

<h2>Detecting Leaks</h2>

<p>When instruments loads your application, you will see the <strong>ObjectAlloc</strong> track start to fill in. To detect the leaks in your project, click on the <strong>Leaks</strong> track and then watch the <strong>Leak Status</strong> category which will detect leaks after the current timeout value. Alternatively, you can just click the <strong>Check For Leaks Now</strong> button under the <strong>Check Manually</strong> category.</p>

<p><img src='http://www.cimgf.com/wp-content/uploads/2008/04/leaks_info.png' alt='Leaks Info' style='text-align: center;'/><br /></p>

<p>Once the leak detection process has occurred you will see a list of objects that are currently leaking. To get details for any leaks in the list, click the object in the list and then click the <em>Extended Detail</em> button at the bottom of the Instruments screen.
<br />
<a href='http://www.cimgf.com/wp-content/uploads/2008/04/extended_detail_button.png' title='Extended Detail' rel='lightbox'><img src='http://www.cimgf.com/wp-content/uploads/2008/04/extended_detail_button.thumbnail.png' alt='Extended Detail' /></a></p>

<p>Once you have clicked the Extended Detail button, you will see the stack trace list on the right side of the Instruments window. Look through the stack and locate any code highlighted with the color #CCFFFF which looks like this.</p>

<p><img src='http://www.cimgf.com/wp-content/uploads/2008/04/ccffff.png' alt='#CCFFFF' /><br /><img src='http://www.cimgf.com/wp-content/uploads/2008/04/leak.png' alt='Leak' /></p>

<hr />

<blockquote><strong>Note:</strong> This is actually inaccurate. The color may be different on your machine than on mine. Instead of looking for a color, look for your applications name and path and double-click that instead.<a href='http://www.cimgf.com/wp-content/uploads/2008/04/stack_mouseover.png' title='Stack Mouse Over' rel='lightbox'><img src='http://www.cimgf.com/wp-content/uploads/2008/04/stack_mouseover.png' alt='Stack Mouse Over' /></a><br />
Thanks to Jason for pointing out the error.</blockquote>

<hr />

<p>Once you find the leak in your application, simply double click it and Instruments will return you to the exact line in XCode where the leak is happening.</p>

<p><a href='http://www.cimgf.com/wp-content/uploads/2008/04/leak_stack.png' title='Leak Stack' rel='lightbox'><img src='http://www.cimgf.com/wp-content/uploads/2008/04/leak_stack.thumbnail.png' alt='Leak Stack' /></a></p>

<p>To fix the leak, you need to make sure that you release the object. For more information and basic guidelines on memory allocation and deallocation, do a Google search. You can start with sites like this one: <a href="http://www.stepwise.com/Articles/Technical/2001-03-11.01.html">Very simple rules for memory management in Cocoa</a>.</p>

<h2>Conclusion</h2>

<p>Finding and fixing issues is not the most glamorous aspect of application development, however, when done, the results are very rewarding. Instruments provides a streamlined way to track everything you would care about in your application. Watch this site for more tutorials on how to use other components available in Instruments. If you want to get an idea of what&#8217;s available, click on the <strong>Library</strong> button in Instruments and scroll through the ensuing list. It&#8217;s impressive.</p>

<p><img src='http://www.cimgf.com/wp-content/uploads/2008/04/library.png' alt='Instruments Library' /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/04/02/cocoa-tutorial-fixing-memory-leaks-with-instruments/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Cocoa Tutorial: awakeFromNib vs applicationDidFinishLaunching</title>
		<link>http://www.cimgf.com/2008/03/26/cocoa-tutorial-awakefromnib-vs-applicationdidfinishlaunching/</link>
		<comments>http://www.cimgf.com/2008/03/26/cocoa-tutorial-awakefromnib-vs-applicationdidfinishlaunching/#comments</comments>
		<pubDate>Wed, 26 Mar 2008 22:35:38 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[awakeFromNib vs applicationDidFinishLaunching]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/2008/03/26/cocoa-tutorial-awakefromnib-vs-applicationdidfinishlaunching/</guid>
		<description><![CDATA[When developing an application in Objective-C and using Cocoa, there is a lot of &#8220;magic&#8221; that happens in the background. As we get more comfortable with the language and the APIs, we begin to discover the source of that magic and understand not only WHY it works but HOW it works. One of those areas [...]]]></description>
			<content:encoded><![CDATA[<p>When developing an application in Objective-C and using Cocoa, there is a lot of &#8220;magic&#8221; that happens in the background.  As we get more comfortable with the language and the APIs, we begin to discover the source of that magic and understand not only WHY it works but HOW it works.</p>

<p>One of those areas is the initialization and callbacks from the nib files to my code.  Normally, when I want a controller to do something after the NIB/XIB has loaded, I add the method <strong>-(void)awakeFromNib</strong> and know that I will receive a call when all of the connections into the NIB/XIB are complete. But on what object does this get called and how?</p>

<p><span id="more-71"></span></p>

<p>In another case, I can be notified when the application has finished launching.  This method, <strong>-(void)applicationDidFinishLaunching:(NSNotification*)aNotification</strong> gets called after the MainMenu.[nib|xib] has finished loading.  How does this method get called and on who does it get called?</p>

<p>And the third question.  If I am using both of these spells above, which gets called first and why?</p>

<h2>awakeFromNib</h2>

<p>awakeFromNib is called on every object that is initialized or referenced from within a nib file.  For example, take a look at the following nib file:</p>

<p align='center'><a href='http://www.cimgf.com/wp-content/uploads/2008/03/afnvadfl_nib_example.png' rel="lightbox"  title='afnvadfl_nib_example.png'><img src='http://www.cimgf.com/wp-content/uploads/2008/03/afnvadfl_nib_example.png' width='75%' alt='afnvadfl_nib_example.png' /><br/>Image 1</a></p>

<p>In this nib file, I have references to two pieces of custom code: The Window Controller and the Window itself.  So which of these two gets the awakeFromNib call?  Both do.</p>

<p>Specifically, when a nib file has completed initializing all of the objects, it then loops back through every object referenced in the nib and if the object responds to awakeFromNib, it calls awakeFromNib on the object.  Therefore, you can have logic in any or all of your objects in the awakeFromNib call.</p>

<h2>applicationDidFinishLaunching:</h2>

<p>In the nib above, which object would receive a applicationDidFinishLaunching: call?  None of them.  The nib in that example is not set up to be the primary nib for an application.  When a nib is designed to be the primary or initial nib for an application it will have a reference to NSApplication in it.</p>

<p align='center'><a href='http://www.cimgf.com/wp-content/uploads/2008/03/afnvadfl_app_example1.png' rel="lightbox"  title='afnvadfl_app_example.png'><img src='http://www.cimgf.com/wp-content/uploads/2008/03/afnvadfl_app_example1.png' width='75%' alt='afnvadfl_app_example.png' /><br/>Image 2</a></p>

<p>In this example you can see the reference to the NSApplication in the nib.  This nib is designed to be the initial nib loaded by the application.  This can be confirmed by looking at the File&#8217;s Owner class type and see that it points to NSApplication rather than an NSObject or some custom controller class (Image 3).  So who gets the applicationDidFinishLaunching: call?  While you cannot see it in the image above, the object &#8216;AppDelegate&#8217; is referenced as the delegate for the NSApplication.</p>

<p align='center'>
<a href='http://www.cimgf.com/wp-content/uploads/2008/03/afmvadfl_app_reference1.png' rel='lightbox' title='afmvadfl_app_reference1.png'><img src='http://www.cimgf.com/wp-content/uploads/2008/03/afmvadfl_app_reference1.png' alt='afmvadfl_app_reference1.png' /><br/>Image 3</a>
</p>

<p align='center'><a href='http://www.cimgf.com/wp-content/uploads/2008/03/afnvadfl_appdelegate.png' rel="lightbox"  title='afnvadfl_appdelegate.png'><img src='http://www.cimgf.com/wp-content/uploads/2008/03/afnvadfl_appdelegate.png'  alt='afnvadfl_appdelegate.png' /><br/>Image 4</a>
</p>

<p>Therefore, when the application has indeed finished launching, then this method on the AppDelegate and only the AppDelegate will be called.  Only one object gets this method per application launch.</p>

<h2>Call order</h2>

<p>In the second example above, it is possible to have an awakeFromNib method and an applicationDidFinishLaunching: method in the AppDelegate.  Which would be called first and why?</p>

<p>The answer is that the awakeFromNib will be called first.  When the nib file has been initialized, each object referenced in the nib will be looped through and they will all receive an awakeFromNib call if they respond to the message.  After all of that is done then the Application&#8217;s delegate will receive the applicationDidFinishLaunching: call.  This is the notice that everything is loaded and that the application is ready to start receiving user input.</p>

<h2>Conclusion</h2>

<p>If your code is localized to only the object you are working with then putting the code in the awakeFromNib is the perfect place for it.  However, if your code is going to be manipulating more than one object in the nib then it is probably safer to put it in the applicationDidFinishLaunching: instead.  This will insure that everything is loaded, referenced and ready to go.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/03/26/cocoa-tutorial-awakefromnib-vs-applicationdidfinishlaunching/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Does Objective-C Perform Autoboxing on Primitives?</title>
		<link>http://www.cimgf.com/2008/03/01/does-objective-c-perform-autoboxing-on-primitives/</link>
		<comments>http://www.cimgf.com/2008/03/01/does-objective-c-perform-autoboxing-on-primitives/#comments</comments>
		<pubDate>Sat, 01 Mar 2008 05:00:13 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Threading]]></category>
		<category><![CDATA[autoboxing]]></category>
		<category><![CDATA[boxing]]></category>
		<category><![CDATA[unboxing]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/2008/03/01/does-objective-c-perform-autoboxing-on-primitives/</guid>
		<description><![CDATA[This article is inaccurate. The writer was smoking crack or something when he wrote it and has not been able to duplicate his tests since. This article is left here for historical reasons. One of the things about Objective-C that I find extremely useful is the ability to resolve a method call at runtime. In [...]]]></description>
			<content:encoded><![CDATA[<p><center></p>

<h1>This article is inaccurate.</h1>

<p></center>
<i>The writer was smoking crack or something when he wrote it and has not been able to duplicate his tests since.  This article is left here for historical reasons.</i></p>

<p>One of the things about Objective-C that I find extremely useful is the ability to resolve a method call at runtime.  In addition this same functionality allows us to do some fairly creative things with callbacks, passing messages between threads, etc.</p>

<p>However there is a bit of a trick when it comes to passing primitives though some of these methods.  For example, one method that I use quite frequently is performSelectorOnMainThread:withObject:waitUntilDone:.  How exactly does one pass a BOOL or an int to this method?
<span id="more-33"></span></p>

<p>Fortunately, this is actually very simple.  While Objective-C does not have the ability to autobox primitives, it will <em>unbox them</em> in this situation.  For example, if you had the following method:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>updateCounter<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span><span style="color: #002200;">&#41;</span>counter
<span style="color: #002200;">&#123;</span>
    <span style="color: #11740a; font-style: italic;">//Do something clever</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>And you needed to call it from a background thread but it needed to be performed on the main thread, all you need to do is:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>aMethodOnABackgroundThread
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">int</span> myInt <span style="color: #002200;">=</span> <span style="color: #2400d9;">12</span>;
    <span style="color: #002200;">&#91;</span>self performSelector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>updateCounter<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span>
               withObject<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><span style="color: #400080;">NSNumber</span> numberWithInt<span style="color: #002200;">:</span>myInt<span style="color: #002200;">&#93;</span>
            waitUntilDone<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>As you can see, we are passing a NSNumber object into the method.  So what is the method actually receiving?  It will receive a primitive int just as it expects to.  No additional work is required in the receiving method.</p>

<p>This same unboxing can be performed with any primitive including BOOL.  Simply wrap them in a NSNumber and pass the NSNumnber through the method call.</p>

<p>As always, there is an exception to the rule.  When you are building your own NSInvocation (the magic Class behind these callbacks) you do not need to pass it an object for a primitive.</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>aMethodOnABackgroundThread
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">int</span> myInt <span style="color: #002200;">=</span> <span style="color: #2400d9;">12</span>;
    <span style="color: #a61390;">SEL</span> sel <span style="color: #002200;">=</span> <span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>updateCounter<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #400080;">NSMethodSignature</span> <span style="color: #002200;">*</span>sig <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self methodSignatureForSelector<span style="color: #002200;">:</span>sel<span style="color: #002200;">&#93;</span>;
    <span style="color: #400080;">NSInvocation</span> <span style="color: #002200;">*</span>invocation <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #400080;">NSInvocation</span> invocationWithMethodSignature<span style="color: #002200;">:</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>invocation setTarget<span style="color: #002200;">:</span>self<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>invocation setSelector<span style="color: #002200;">:</span>sel<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>invocation setArgument<span style="color: #002200;">:&amp;</span>myInt atIndex<span style="color: #002200;">:</span><span style="color: #2400d9;">2</span><span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>invocation invoke<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>In this example, the NSNumber wrapper/boxing is unnecessary as the invocation accepts anything.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/03/01/does-objective-c-perform-autoboxing-on-primitives/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Cocoa Coding Practice: Old School vs New</title>
		<link>http://www.cimgf.com/2008/02/20/cocoa-coding-practice-old-school-vs-new/</link>
		<comments>http://www.cimgf.com/2008/02/20/cocoa-coding-practice-old-school-vs-new/#comments</comments>
		<pubDate>Wed, 20 Feb 2008 05:00:09 +0000</pubDate>
		<dc:creator>Marcus Zarra</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Coding Practice]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[dealloc]]></category>
		<category><![CDATA[memory management]]></category>

		<guid isPermaLink="false">http://www.cimgf.com/2008/02/20/cocoa-coding-practice-old-school-vs-new/</guid>
		<description><![CDATA[This post is in response to a few queries that I have received regarding my last post showing an NSOperation example. One of the questions raised that I will focus on is my -(void)dealloc method in the NSOperation subclass. The questions boiled down to: Why are you using releases at all. Garbage collection is the [...]]]></description>
			<content:encoded><![CDATA[<p><img src='http://www.cimgf.com/wp-content/uploads/2008/02/garbage_collection_thumb.jpg' alt='Garbage Collection' / align="left" style="margin:5px;"></p>

<p>This post is in response to a few queries that I have received regarding <a href="http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/">my last post showing an NSOperation example</a>.  One of the questions raised that I will focus on is my <strong>-(void)dealloc</strong> method in the NSOperation subclass.  The questions boiled down to:</p>

<p><em>Why are you using releases at all.  Garbage collection is the future!</em></p>

<p>and</p>

<p><em>You should be just doing</em> <strong>[self setVar:nil]</strong> <em>instead of that</em> <strong>[var release], var = nil;</strong> <em>crap.</em></p>

<p><span id="more-27"></span></p>

<h2>Garbage Collection</h2>

<p>Regarding garbage collection&#8211;currently I am not using it in any of my production code. <a href="http://www.zarrastudios.com/ZDS/seSales.html">seSales</a> is still backwards compatible with Tiger and will remain so for now.  <a href="http://www.zarrastudios.com/ZDS/iWebBuddy.html">iWebBuddy</a>, however, uses the dotMac SDK quite heavily and therefore it cannot use garbage collection since that SDK is not compatible (yet).  Even if I were to start using garbage collection tomorrow I would still be writing dealloc methods, adding autorelease to temporary variables, etc.</p>

<p>The reason for this is simple&#8211;it makes the code compatible with both garbage collected and non-garbage collected compiles.  I can turn gc on and off without having to go through my code and re-adding all of the memory management.  Since Apple was wise enough to make all of the  memory calls no-ops with gc turned on <strong>it does not hurt anything to leave them in!</strong>  Since I am a former Java developer, I do not trust garbage collection yet.  That may and probably will change in the future but for now, I am watching it very closely.</p>

<h2>dealloc and releasing objects</h2>

<p>For the second question regarding how I handle my dealloc methods.  This requires a little bit more explanation but the short answer is &#8212; I am used to doing them that way.</p>

<p>For the longer answer, we have to look at what Objective-C is synthesizing my <strong>@property(retain) NSURL *targetURL;</strong> into.  The resulting setter for this property is something very similar to:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setTargetURL<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #400080;">NSURL</span><span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>url
<span style="color: #002200;">&#123;</span>
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>url <span style="color: #002200;">==</span> targetURL<span style="color: #002200;">&#41;</span> <span style="color: #a61390;">return</span>;
    <span style="color: #002200;">&#91;</span>url retain<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>targetURL release<span style="color: #002200;">&#93;</span>;
    targetURL <span style="color: #002200;">=</span> url;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>If that looks familiar to you, it should.  We have been writing setter methods like that for years.  So when I call <strong>[self setTargetURL:nil]</strong> from my dealloc method, it is really doing 3 message calls, an assignment and a conditional&#8211;as opposed to my normal release code which is:</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>dealloc
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>targetURL release<span style="color: #002200;">&#93;</span>, targetURL <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
    <span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>


<p>In my release there is one message and one assignment.  So it is shorter and faster.  Of course with modern hardware the difference between these two is negligible.</p>

<h2>Conclusion</h2>

<p>So which way is better?  Neither and both.  My coding style is born out of years of habit.  To change it now for no gain is a waste of energy and risks introducing bugs into my code that would not otherwise be there.  If there was something to be gained from changing the way I handle memory or the way I release my objects then I would absolutely relearn it.  While the upgrades to Objective-C in Leopard are great, and I use many of them, they do not force me to change my habits with regard to memory management.  And that, in my opinion, is a great thing.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cimgf.com/2008/02/20/cocoa-coding-practice-old-school-vs-new/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
