<?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>Vincent Gable's Blog &#187; Best Practices</title>
	<atom:link href="http://vgable.com/blog/tag/best-practices/feed/" rel="self" type="application/rss+xml" />
	<link>http://vgable.com/blog</link>
	<description>my weblog.</description>
	<lastBuildDate>Tue, 29 Nov 2011 22:20:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>My UIViewController Template</title>
		<link>http://vgable.com/blog/2010/08/15/my-uiviewcontroller-template/</link>
		<comments>http://vgable.com/blog/2010/08/15/my-uiviewcontroller-template/#comments</comments>
		<pubDate>Mon, 16 Aug 2010 03:09:40 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Template]]></category>
		<category><![CDATA[UIViewController]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=666</guid>
		<description><![CDATA[I haven&#8217;t formalized this as a proper Xcode template, but this is what&#8217;s in my PrototypeViewController.m file that I copy/paste over the UIViewController subclasses Xcode makes. @interface MyViewController () @end @implementation MyViewController - (void) releaseViewObjects; { if([[self superclass] instancesRespondToSelector:@selector(releaseViewObjects)]) [(id)super releaseViewObjects]; } - (void)viewDidUnload; { [super viewDidUnload]; [self releaseViewObjects]; } - (void)dealloc; { [self releaseViewObjects]; [...]]]></description>
			<content:encoded><![CDATA[<p>I haven&#8217;t formalized this as a proper Xcode template, but this is what&#8217;s in my <code>PrototypeViewController.m</code> file that I copy/paste over the <code>UIViewController</code> subclasses Xcode makes.</p>
<div class="code-box">
<pre>

@interface MyViewController ()
@end

@implementation MyViewController
- (void) releaseViewObjects;
{
	if([[self superclass] instancesRespondToSelector:@selector(releaseViewObjects)])
		[(id)super releaseViewObjects];
}

- (void)viewDidUnload;
{
    [super viewDidUnload];
    [self releaseViewObjects];
}

- (void)dealloc;
{
    [self releaseViewObjects];
    [super dealloc];
}

@end
</pre>
</div>
<p>Here are the reasons why, in no particular order:</p>
<h3>Commented-Out Code is Evil</h3>
<p>Littering source code with &#8220;comments&#8221; full of crufty, obsolete, or unimplemented code is not a good thing. <strong>Xcode&#8217;s default template is full of commented-out code</strong>. If you&#8217;re totally new to the platform, starting from the templates aren&#8217;t a bad way to learn.  But in my experiance, they do harm to a production code-base, by injecting hundreds of lines of commented-out code into a project.</p>
<h3>Share code between <code>viewDidUnload</code> and <code>dealloc</code> With <code> releaseViewObjects </code></h3>
<p>In my world, <code>releaseViewObjects</code> is <strong>solely responsible</strong> for cleaning up every <code>IBOutlet</code>, and any objects created in <code>viewDidLoad</code>.</p>
<p>There are technical reasons why this is a little scary. Calling a method in <code>dealloc</code> is potentially risky, because the object may be in an invalid half-torn-down state, and because <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html">Dark Runtime Magicks</a> could be afoot (see <a href="http://www.mikeash.com/pyblog/friday-qa-2009-11-27-using-accessors-in-init-and-dealloc.html"><cite>Using Accessors in Init and Dealloc</cite></a>.)</p>
<p>But in my experience, such bugs, although as scary as they sound, are rare corner-cases and still quite fixable. But <em>every</em> <code>UIViewController</code> needs to clean up after itself, so simplifying the universally common case is a net win.</p>
<p>The <code>if([[self superclass] instancesRespondToSelector:@selector(releaseViewObjects)])</code> test wouldn&#8217;t be necessary if I added another class between <code>UIViewController</code> and my real code, so that I was sure my class&#8217; <code>super</code> implemented <code>releaseViewObjects</code>. But adding a subclass just to implement one empty method, to avoid a two-line test, isn&#8217;t worth it.</p>
<p>The <code>(id)super</code> cast is intentional, to prevent compiler warnings.</p>
<p>I have to use the more complex <code>[[self superclass] instancesRespondToSelector:</code> test, because <code>-[super respondsToSelector:]</code> <a href="http://www.cocoabuilder.com/archive/cocoa/208788-super-respondstoselector.html">doesn&#8217;t work</a>.</p>
<h3>I Won&#8217;t <em>Really</em> Get To <code>didReceiveMemoryWarning</code></h3>
<p>I&#8217;m not proud to admit this, but it&#8217;s true. We&#8217;ve all been told that a good iPhone program <em>must</em> release resources when it gets a memory warning, or else it will be killed. But in practice, there have always been better places to spend my time (or at least it sure feels that way!) Spending a few hours in Instruments to fix leaks prevents memory warnings in the first place, and that&#8217;s a bigger win.</p>
<p>Besides, <strong>80% of what <code>didReceiveMemoryWarning</code> would do is handled in <code> releaseViewObjects</code></strong>, which is automatically called by the default implementation.</p>
<p>So I break with Xcode and leave <code>didReceiveMemoryWarning</code> out of my template, because <em>the default class won&#8217;t use it</em>.</p>
<h3>What About <code>init</code>?</h3>
<p>I don&#8217;t have a default <code>init(With…)</code> method. <strong>I try to use <code>autorelease</code>-ed objects everywhere I can</strong>, so I&#8217;m more comfortable implementing <code>+[MyViewController viewControllerForFoo:]</code>.</p>
<p>But I don&#8217;t have a default constructor of <em>any</em> kind, because <strong>a constructor should take every value it <em>needs</em></strong>, and I don&#8217;t know what these values are until I&#8217;ve written a bit more of the class. It&#8217;s a chicken and egg problem.</p>
<p>Once I&#8217;ve written out a bit more of the class, I&#8217;ll usually build something that looks like:</p>
<div class="code-box">
<pre>
+ (RouteMapViewController*) routeMapViewControllerWithWaypoints:(NSArray*)waypoints mapRegion:(MKCoordinateRegion)region;
{
	RouteMapViewController *vc = [[[self class] new] autorelease];
	vc.title = NSLocalizedString(@"The Path",@"");
	vc.hidesBottomBarWhenPushed = YES;
	vc.waypoints = waypoints;
	vc.mapRegion = region;
	return vc;
}
</pre>
</div>
<p>For what it&#8217;s worth I <a href="http://weblog.bignerdranch.com/?p=56">use this pattern to implement a 0-argument <code>-init</code></a>.</p>
<h3>Empty Class Extension</h3>
<p><a href="http://www.friday.com/bbum/2009/09/11/class-extensions-explained/">Class extensions</a> are the best way to have &#8220;private&#8221; things in Objective-C. They let the compiler catch objects using another object&#8217;s private methods. They let a class have publicly <code>readonly</code>, but internally <code>readwrite</code>, properties.</p>
<p>Bottom line: every nontrivial object I&#8217;ve written uses them, so they&#8217;re in my template.</p>
<h3>Nothing Else (For Now)</h3>
<p>My template is smaller than Xcode&#8217;s. That is by design. Outside of <a href="http://js1k.com/">esoteric contests</a>, having less code to maintain is a good thing. So <strong>I prefer a template that tries very hard to avoid adding code I don&#8217;t need.</strong></p>
<p>Do you disagree with any of my choices? Please <strong>leave a comment explaining why</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2010/08/15/my-uiviewcontroller-template/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>#define String</title>
		<link>http://vgable.com/blog/2010/07/19/define-string/</link>
		<comments>http://vgable.com/blog/2010/07/19/define-string/#comments</comments>
		<pubDate>Tue, 20 Jul 2010 04:56:19 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Bug Bite]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[MacOSX]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Constants]]></category>
		<category><![CDATA[macros]]></category>
		<category><![CDATA[NSString]]></category>
		<category><![CDATA[Programming Style]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=658</guid>
		<description><![CDATA[When I need a string-constant, I #define it, instead of doing the &#8220;right&#8221; thing and using an extern const NSString * variable. UPDATE 2010-07-20 Thanks to Elfred Pagen for pointing out that you should always put () around your macros. Wrong: #define A_STRING @"hello" instead use (), even when you don&#8217;t think you have to: [...]]]></description>
			<content:encoded><![CDATA[<p>When I need a string-constant, I <code>#define</code> it, instead of doing the &#8220;right&#8221; thing and using an <code>extern const NSString *</code> variable.</p>
<p><H3>UPDATE 2010-07-20</H3> Thanks to <a href="http://twitter.com/elfredpagan">Elfred Pagen</a> for pointing out that you should <strong>always put () around your macros</strong>. Wrong: <del><code>#define A_STRING @"hello"</code></del></p>
<p>instead use (), even when you don&#8217;t think you have to:</p>
<p><code>#define A_STRING (@"hello")</code></p>
<p>This prevents <strong>accidental string concatenation</strong>. In C, string-literals separated only by whitespace are implicitly concatenated. It&#8217;s the same with Objective-C string literals.  This feature lets you break long strings up into several lines, so <code>NSString *x = @"A long string!"</code> can be rewritten:</p>
<div class="code-box">
<pre>
NSString *x =
	@"A long"
	@" string!";
</pre>
</div>
<p>Unfortunately, this seldom-used feature can backfire in unexpected ways. Consider making an array of two strings:</p>
<div class="code-box">
<pre>
#define X @"ex"
#define P @"plain"
a = [NSArray arrayWithObjects:X
                              P,
                              nil];
</pre>
</div>
<p>That <em>looks</em> right, but I forgot a &#8220;<code>,</code>&#8221; after <code>X</code>, so after string-concatenation, <code>a</code> is <code>['explain']</code>, not <code>['ex','plain']</code>.</p>
<p>Moral of the story: <strong>you can never have too many ()&#8217;s in macros</strong>.</p>
<p>And, now, back to why I use <code>#define</code>&#8230;</p>
<h3>It&#8217;s less code</h3>
<p>Using an <code>extern</code> variable means declaring it in a header, <em>and</em> defining it in some implementation file. But a macro is just one line in a header.</p>
<h3>It&#8217;s faster to lookup</h3>
<p>Because there&#8217;s only the definition of a macro, Open Quickly/command-double-clicking a macro <em>always</em> jumps to the definition, so you can see what it&#8217;s value is in one step. Generally Xcode jumps to a symbol&#8217;s declaration first, and <em>then</em> it&#8217;s definition, making it slower to lookup the value of a <code>const</code> symbol.</p>
<h3>It&#8217;s still type safe</h3>
<p>An <code>@"NSString literal"</code> has type information, so mistakes like,</p>
<pre>#define X (@"immutable string")
NSMutableString *y = X;
[y appendString:@"z"];
</pre>
<p>still generate warnings.</p>
<h3>It lets the compiler <a href="http://bobthegnome.blogspot.com/2009/07/format-not-string-literal-and-no-format.html">check format-strings</a></h3>
<p>Xcode can catch errors like &#8220;<code>[NSString stringWithFormat:@"reading garbage since there's no argument: %s"]</code>&#8220;, <a href="http://vgable.com/blog/2009/12/09/compile-safer/">if you let it</a>. Unfortunately, the Objective-C compiler isn&#8217;t smart enough to check <code>[NSString stringWithFormat:externConstString,x,y,z];</code> because it doesn&#8217;t know what an <code>extern</code> variable contains until link-time. But preprocessor macros are evaluated early enough in the build process that that the compiler can check their values.</p>
<h3>It can&#8217;t be changed at runtime</h3>
<p>It&#8217;s possible to change the value of <code>const</code> variables through pointers, like so:</p>
<div class="code-box">
<pre>
const NSString* const s = @"initial";
NSString **hack = &#038;s;
*hack = @"changed!";
NSLog(s);//prints "changed!"
</pre>
</div>
<p>Yes this is pathological code, but I&#8217;ve seen it happen (I&#8217;m looking at you <code>AddressBook.framework</code>!)</p>
<p>Of course, you can re-<code>#define</code> a preprocessor-symbol, so macros aren&#8217;t a panacea for pathological constant-changing code. (Nothing is!) But they push the pathology into compile time, and common wisdom is that it&#8217;s easier to debug compile-time problems, so that&#8217;s a Good Thing. You may <a href="http://vgable.com/blog/2008/09/18/i-would-rather-have-a-runtime-error-than-a-compile-error/">disagree there</a>, and you may be right! All I can say for sure is that <em>in my experience</em>, I&#8217;ve had bugs from <code>const</code> values changing at runtime, but no bugs from re-<code>#define</code>-ed constants (yet).</p>
<h3>Conclusion</h3>
<p>Preprocessor macros are damnably dangerous in C. Generally you should avoid them. But for <code>NSString*</code> constants in applications, I think they&#8217;re easier, and arguably less error prone. So go ahead and <code>#define YOUR_STRING_CONSTANTS (@"like this")</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2010/07/19/define-string/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NSHomeDirectory() is a Bad Thing</title>
		<link>http://vgable.com/blog/2010/06/02/nshomedirectory-is-a-bad-thing/</link>
		<comments>http://vgable.com/blog/2010/06/02/nshomedirectory-is-a-bad-thing/#comments</comments>
		<pubDate>Wed, 02 Jun 2010 08:08:54 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Announcement]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[MacOSX]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[NSHomeDirectory]]></category>
		<category><![CDATA[Paths]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=611</guid>
		<description><![CDATA[Code that uses NSHomeDirectory() is probably doing The Wrong Thing. It&#8217;s not appropriate to clutter up the user&#8217;s home directory &#8212; internal application-data should be stored in the Application Support directory (or a temporary file if it&#8217;s transient). So I can&#8217;t think of a good reason to get the path to the user&#8217;s home directory. [...]]]></description>
			<content:encoded><![CDATA[<p>Code that uses <code>NSHomeDirectory()</code> is probably doing The Wrong Thing. It&#8217;s not appropriate to clutter up the user&#8217;s home directory &#8212; internal application-data should be stored in the <a href="http://cocoawithlove.com/2010/05/finding-or-creating-application-support.html"><code>Application Support</code> directory</a> (or a <a href="http://stackoverflow.com/questions/215820/how-do-i-create-a-temporary-file-with-cocoa">temporary file</a> if it&#8217;s transient). So I can&#8217;t think of a good reason to get the path to the user&#8217;s home directory. <strong>Every use of <code>NSHomeDirectory()</code> I&#8217;ve seen is spamming the home directory, or getting a subdirectory in a brittle way.</strong></p>
<p>For sample code that gets a directory robustly, using <code> NSSearchPathForDirectoriesInDomains()</code>, see <a href="http://cocoawithlove.com/2010/05/finding-or-creating-application-support.html"><cite>Finding or creating the application support directory</cite></a>.</p>
<p>Because <code>NSHomeDirectory()</code> encourages so many bad practices, it should be deprecated.</p>
<h3>Disabling <code> NSHomeDirectory()</code> in Your Projects</h3>
<p>Add the following macro to your prefix file:</p>
<div class="codebox" style="overflow:scroll">
<pre>#define NSHomeDirectory() NSHomeDirectory_IS_DISCOURAGED_USE_NSSearchPathForDirectoriesInDomains_TO_GET_A_SUBDIRECTORY_OF_HOME</pre>
</div>
<p>Then any use of <code>NSHomeDirectory()</code> will give the compiler error:</p>
<div style="overflow:scroll">
<blockquote><p>error:<br />
&#8216;NSHomeDirectory_IS_DISCOURAGED_USE_NSSearchPathForDirectoriesInDomains_TO_GET_A_SUBDIRECTORY_OF_HOME&#8217; undeclared (first use in this function)
</p></blockquote>
</div>
<h3>Tell Me I&#8217;m Wrong</h3>
<p><strong>If you&#8217;ve seen a legitimate use of <code>NSHomeDirectory()</code> please leave a comment!</strong> Just because I can&#8217;t think of one doesn&#8217;t mean they don&#8217;t exist.</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2010/06/02/nshomedirectory-is-a-bad-thing/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>drain an NSAutoReleasePool Don&#8217;t release it</title>
		<link>http://vgable.com/blog/2010/05/26/drain-an-nsautoreleasepool-dont-release-it/</link>
		<comments>http://vgable.com/blog/2010/05/26/drain-an-nsautoreleasepool-dont-release-it/#comments</comments>
		<pubDate>Thu, 27 May 2010 02:43:35 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[iPhone]]></category>
		<category><![CDATA[MacOSX]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Garbage Collection]]></category>
		<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[NSAutoreleasePool]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=609</guid>
		<description><![CDATA[To clean up an NSAutoreleasePool, do [pool drain]; not [pool release]; In a garbage-collected environment, sending any object a release message is hardcoded by the runtime to do nothing (very quickly). So [pool release] won&#8217;t do anything. But [pool drain] will signal the garbage collector to cleanup, and works correctly (just like release) in a [...]]]></description>
			<content:encoded><![CDATA[<p><strong>To clean up an <code>NSAutoreleasePool</code>, do <code>[pool <a href="http://developer.apple.com/iphone/library/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html#//apple_ref/occ/instm/NSAutoreleasePool/drain">drain</a>];</code> <em>not</em> <code>[pool release];</code></strong></p>
<p>In a garbage-collected environment, sending any object a <code>release</code> message is <a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-3-the-fast-path/">hardcoded by the runtime</a> to do nothing (very quickly). So <code>[pool release]</code> won&#8217;t do anything. But <code>[pool drain]</code> will signal the garbage collector to cleanup, and works correctly (just like <code>release</code>) in a non-garbage-collected environment.</p>
<h3>Why This Still Matters on an iPhone</h3>
<p>The iPhone doesn&#8217;t have garbage collection today. That doesn&#8217;t mean it never will. RIM and Android both support some kind of garbage collection. I&#8217;m too grizzled an Apple developer to not future proof my code, because I&#8217;ve been effected by Apple making some major runtime changes (eg. switching between PowerPC, x86, x86_64, and ARM processors). Section 3.3.1 of the iPhone SDK agreement means Apple&#8217;s runtime is the only game in town. It pays to be sure your code <em>always</em> plays nicely with it.</p>
<p>Using <code>drain</code> also helps your code will play nice with Mac OS X. That gives you more options to re-use and monazite it. If you decide to go the open-route, it means more people will be able to use your code.</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2010/05/26/drain-an-nsautoreleasepool-dont-release-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Write dealloc FIRST</title>
		<link>http://vgable.com/blog/2010/05/25/write-dealloc-first/</link>
		<comments>http://vgable.com/blog/2010/05/25/write-dealloc-first/#comments</comments>
		<pubDate>Tue, 25 May 2010 20:32:19 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Bug Bite]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[dealloc]]></category>
		<category><![CDATA[ivars]]></category>
		<category><![CDATA[Memory Management]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=607</guid>
		<description><![CDATA[As soon as you give a class a new instance variable (ivar), update the class&#8217;s dealloc method (and viewDidUnload, if the ivar is an IBOutlet) to clean up the ivar. Do this before you write the code using the new ivar. Here&#8217;s why: Never Forget You can&#8217;t forget to release an ivar, if the code [...]]]></description>
			<content:encoded><![CDATA[<p>As soon as you give a class a new instance variable (ivar), update the class&#8217;s <code>dealloc</code> method (and <code>viewDidUnload</code>, if the ivar is an <code>IBOutlet</code>) to clean up the ivar. Do this <em>before</em> you write the code using the new ivar. Here&#8217;s why:</p>
<h3>Never Forget</h3>
<p>You can&#8217;t forget to <code>release</code> an ivar, if the code that reaps it is in place <em>before</em> the code that creates it. Updating <code>dealloc</code> first means less memory leaks.</p>
<p>Even with an impossibly good testing protocol, that catches <em>every</em> memory leak, it&#8217;s faster to fix memory leaks before they happen than to track them down after the fact.</p>
<h3>You Know More Than They Do</h3>
<p>Sometimes there&#8217;s an important step that must be done when cleaning up an ivar. Maybe you need to set it&#8217;s <code>delegate</code> to <code>nil</code>, or unregister for a notification, or break a <a href="http://www.mikeash.com/pyblog/friday-qa-2010-04-30-dealing-with-retain-cycles.html">retain cycle</a>. You know this when you setup the ivar. But your coworkers don&#8217;t know this <em>a priori</em>. When you checkin code that leaks or triggers an analyzer warning, they&#8217;ll want to fix it, and since they know less than you do about your code, they&#8217;re more likely to miss a crucial step. (Even if you work alone, remember Future You! In <em>N</em> weeks, Future You will have to deal with all the code Present You wrote today &#8230; and they&#8217;ll be in the same situation as any other co-worker, because they won&#8217;t remember everything Present You knows. )</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2010/05/25/write-dealloc-first/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>N.A.R.C.</title>
		<link>http://vgable.com/blog/2010/05/19/n-a-r-c/</link>
		<comments>http://vgable.com/blog/2010/05/19/n-a-r-c/#comments</comments>
		<pubDate>Thu, 20 May 2010 03:25:48 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[MacOSX]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[autorelease]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[retain]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=601</guid>
		<description><![CDATA[How to remember Cocoa memory management: Think NARC: &#8220;New Alloc Retain Copy&#8221;. If you are not doing any of those things, you don&#8217;t need to release. &#8211;Andiih on Stack Overflow Personally, I like to immediately autorelease anything I NARC-ed, on the same line. For example: Foo* pityTheFoo = [[[Foo alloc] init] autorelease]; Admittedly, this makes [...]]]></description>
			<content:encoded><![CDATA[<p>How to remember Cocoa memory management:</p>
<blockquote><p>Think <strong>NARC</strong>: &#8220;New Alloc Retain Copy&#8221;. If you are not doing any of those things, you don&#8217;t need to <code>release</code>.</p></blockquote>
<p>&#8211;Andiih <a href="http://stackoverflow.com/questions/2865185/do-you-need-to-release-parameters-of-methods-at-the-end-of-them-in-objective-c">on Stack Overflow</a></p>
<p>Personally, I like to <em>immediately</em> <code>autorelease</code> anything I NARC-ed, on the same line. For example:</p>
<pre>Foo* pityTheFoo = [[[Foo alloc] init] autorelease];</pre>
<p>Admittedly, this makes for some ugly, bracey, lines. But I think it&#8217;s worth it, because you <em>never</em> having to worry about calling <code>release</code> if you also&#8230;</p>
<h3>Use a <code>@property</code> (or Setter) Instead of <code>retain</code></h3>
<p>In other words I would write an <code>init</code> method that looked like:</p>
<pre>
- (id) init
{
	self = [super init];
	if (self) {
		_ivar = [[Foo alloc] init];
	}
	return self;
}</pre>
<p>as:</p>
<pre>
- (id) init
{
	self = [super init];
	if (self) {
		self._ivar = [[[Foo alloc] init] autorelease];
	}
	return self;
}
</pre>
<p>(Or <code>[self setIvar:[[[Foo alloc] init] autorelease]];</code> if you are one of those folks who hate the dot-syntax.)</p>
<p>It&#8217;s  debatable if <a href="http://www.mikeash.com/pyblog/friday-qa-2009-11-27-using-accessors-in-init-and-dealloc.html">using acessors in <code>init</code> and <code>dealloc</code></a> is a good idea. I even left a comment on that post arguing against it. But since then I&#8217;ve done a lot of reflection, and in my experience using a <code>@property</code> instead of an explicit <code>release</code>/<code>= nil</code> solves more problems then it causes. So I think it&#8217;s the best practice.</p>
<p>Even if you disagree with me on that point, if <strong>the only places you explicitly NARC objects are <code>init</code>, <code>dealloc</code>, and <code>setX:</code> methods</strong> then I think you&#8217;re doing the right thing.</p>
<h3>Cycles!</h3>
<p>The last piece of the memory-management puzzle are <a href="http://www.mikeash.com/pyblog/friday-qa-2010-04-30-dealing-with-retain-cycles.html">retain cycles</a>. By far the best advice I&#8217;ve seen on them is  <a href="http://www.mikeash.com/pyblog/friday-qa-2010-04-30-dealing-with-retain-cycles.html">Mike Ash&#8217;s article</a>. Read it.</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2010/05/19/n-a-r-c/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t Check For nil in Your dealloc Methods</title>
		<link>http://vgable.com/blog/2010/05/17/dont-check-for-nil-in-your-dealloc-methods/</link>
		<comments>http://vgable.com/blog/2010/05/17/dont-check-for-nil-in-your-dealloc-methods/#comments</comments>
		<pubDate>Mon, 17 May 2010 08:58:24 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[nil]]></category>
		<category><![CDATA[Programming Style]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=599</guid>
		<description><![CDATA[There&#8217;s no need to check if a variable is nil before release-ing it, because calling a method on a NULL variable is a no-op in Objective-C. And the runtime already has a super-fast check for this case.  So adding an extra if test into your code will probably slow things down. Doing a pointless &#8220; ==?nil&#8221;  test is bad for two reasons. Firstly, [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s no need to check if a variable is <span style="color: #d000a6; font-family: Menlo; font-size: 11px;">nil</span> before <span style="color: #4a0086; font-family: Menlo; font-size: 11px;">release-</span>ing it, because <a href="http://vgable.com/blog/2008/05/31/messages-to-nowhere/">calling a method on a NULL variable is a no-op in Objective-C</a>. And the runtime already has a <a href="http://www.friday.com/bbum/2009/12/18/objc_msgsend-tour-part-3-the-fast-path/">super-fast check for this case</a>.  So adding an extra <span style="color: #d000a6; font-family: Menlo; font-size: 11px;">if <span style="color: #000000; font-family: Helvetica; font-size: medium;">test into your code will probably slow things down.</span></span></p>
<p>Doing a pointless &#8220; <span style="color: #3c8289; font-family: Menlo; font-size: 11px;"><span style="color: #000000;">==?<span style="color: #3c8289;"><span style="color: #d000a6;">nil<span style="color: #000000; font-family: Helvetica; font-size: medium;">&#8221;  test is bad for two reasons.</span></span></span></span></span></p>
<p><span style="color: #3c8289; font-family: Menlo; font-size: 11px;"><span style="color: #000000;"><span style="color: #3c8289;"><span style="color: #d000a6;"><span style="color: #000000; font-family: Helvetica; font-size: medium;">Firstly, <strong>it&#8217;s <a href="http://www.codinghorror.com/blog/2007/05/the-best-code-is-no-code-at-all.html">more code</a> for no good reason.</strong> Even if it&#8217;s just one more line, It&#8217;s one more line to debug and test. It&#8217;s one more place where something could go wrong.</span></span></span></span></span></p>
<p>Secondly, it&#8217;s not idiomatic Cocoa-code, so <strong>it signals that something strange is going on. <span style="font-weight: normal;">That&#8217;s a problem for whoever is reading the code, because they have to stop and look around more carefully to figure out <em>why the pointless tests are happening</em>.</span></strong></p>
<p>In summary, <strong>do NOT do this</strong>:</p>
<p style="margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo;">- (<span style="color: #d000a6;">void</span>)dealloc;</p>
<p style="margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo;">{</p>
<p style="margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #3c8289;"><span style="color: #000000;"><span style="white-space: pre;"> </span></span><span style="color: #d000a6;">if</span><span style="color: #000000;">(</span>baseImage<span style="color: #000000;">) {</span></p>
<p style="margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #3c8289;"><span style="color: #000000;"><span style="white-space: pre;"> </span>[</span>baseImage<span style="color: #000000;"> </span><span style="color: #4a0086;">release</span><span style="color: #000000;">];</span></p>
<p style="margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #3c8289;"><span style="color: #000000;"><span style="white-space: pre;"> </span></span>baseImage<span style="color: #000000;"> = </span><span style="color: #d000a6;">nil</span><span style="color: #000000;">;</span></p>
<p style="margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo;"><span style="white-space: pre;"> </span>}</p>
<p style="margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #4a0086;"><span style="color: #000000;"><span style="white-space: pre;"> </span>[</span><span style="color: #d000a6;">super</span><span style="color: #000000;"> </span>dealloc<span style="color: #000000;">];</span></p>
<p style="margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo;">}?</p>
<p><strong>Do this:</strong></p>
<p><p style="margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo;">- (<span style="color: #d000a6;">void</span>)dealloc;</p>
<p style="margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo;">{</p>
<p style="margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #3c8289;"><span style="color: #000000;"><span style="white-space: pre;"> </span>[</span>baseImage<span style="color: #000000;"> </span><span style="color: #4a0086;">release</span><span style="color: #000000;">];</span></p>
<p style="margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #3c8289;"><span style="color: #000000;"><span style="white-space: pre;"> </span></span>baseImage<span style="color: #000000;"> = </span><span style="color: #d000a6;">nil</span><span style="color: #000000;">;</span></p>
<p style="margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo; color: #4a0086;"><span style="color: #000000;"><span style="white-space: pre;"> </span>[</span><span style="color: #d000a6;">super</span><span style="color: #000000;"> </span>dealloc<span style="color: #000000;">];</span></p>
<p style="margin: 0.0px 0.0px 0.0px 0.0px; font: 11.0px Menlo;">}</p></p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2010/05/17/dont-check-for-nil-in-your-dealloc-methods/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>-[NSURL isEqual:] Gotcha</title>
		<link>http://vgable.com/blog/2009/04/22/nsurl-isequal-gotcha/</link>
		<comments>http://vgable.com/blog/2009/04/22/nsurl-isequal-gotcha/#comments</comments>
		<pubDate>Thu, 23 Apr 2009 00:05:07 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Bug Bite]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[MacOSX]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[isEqual:]]></category>
		<category><![CDATA[NSArray]]></category>
		<category><![CDATA[NSDictionary]]></category>
		<category><![CDATA[NSSet]]></category>
		<category><![CDATA[NSString]]></category>
		<category><![CDATA[NSURL]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/2009/04/22/nsurl-isequal-gotcha/</guid>
		<description><![CDATA[BREAKING UPDATE: Actually comparing the -absoluteURL or -absoluteString of two NSURLs that represent a file is not good enough. One may start file:///, and the other file://localhost/, and they will not be isEqual:! A work around is to compare the path of each NSURL. I&#8217;m still looking into the issue, but for now I am [...]]]></description>
			<content:encoded><![CDATA[<p>BREAKING UPDATE: Actually comparing the <code>-absoluteURL</code> or <code>-absoluteString</code> of two <code>NSURL</code>s that represent a file is <em>not good enough</em>.  One may start <code>file:///</code>, and the other <code>file://localhost/</code>, and <em>they will not be <code>isEqual:</code></em>!  A work around is to compare the <code>path</code> of each <code>NSURL</code>. I&#8217;m still looking into the issue, but for now I am using the following method to compare <code>NSURL</code>s.</p>
<pre>@implementation NSURL (IsEqualTesting)
- (BOOL) isEqualToURL:(NSURL*)otherURL;
{
	return [[self absoluteURL] isEqual:[otherURL absoluteURL]] ||
	[self isFileURL] &#038;&#038; [otherURL isFileURL] &#038;&#038;
	([[self path] isEqual:[otherURL path]]);
}
@end
</pre>
<p><code>[a isEqual:b]</code> may report <code>NO</code> for two <code>NSURL</code>s that both resolve to the same resource (website, file, whatever). So <strong>compare <code>NSURL</code>s like <code>[[a absoluteString] isEqual:[b absoluteString]]</code></strong>. It&#8217;s important to be aware of this gotcha, because URLs are Apple&#8217;s preferred way to represent file paths, and APIs are starting to require them. <strong>Equality tests that worked for <code>NSString</code> file-paths may fail with <code>NSURL</code> file-paths.</strong></p>
<p><a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURL/isEqual:">The official documentation says</a></p>
<blockquote><p> two <code>NSURLs</code> are considered equal if they both have the same base <a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURL/baseURL"><code>baseURL</code></a> and <a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURL/relativeString"><code>relativeString</code></a>.</p></blockquote>
<p>Furthermore,</p>
<blockquote><p>An <code>NSURL</code> object is composed of two parts—a potentially nil base URL and a string that is resolved relative to the base URL. An <code>NSURL</code> object whose string is fully resolved without a base is considered absolute; all others are considered relative.
</p></blockquote>
<p>In other words, two <code>NSURL</code> objects can resolve to the same absolute URL, but have a different base URL, and be considered <code>!isEqual:</code>.</p>
<p>An example should make this all clear,</p>
<pre>
NSURL *VGableDotCom = [NSURL URLWithString:@"http://vgable.com"];
NSURL *a = [[NSURL alloc] initWithString:@"blog" relativeToURL:VGableDotCom];
NSURL *b = [[NSURL alloc] initWithString:@"http://vgable.com/blog" relativeToURL:nil];
<a href="http://vgable.com/blog/2008/08/05/simpler-logging-2/">LOG_INT</a>([a isEqual:b]);
<a href="http://vgable.com/blog/2008/08/05/simpler-logging-2/">LOG_INT</a>([[a absoluteURL] isEqual:[b absoluteURL]]);
<a href="http://vgable.com/blog/2008/08/05/simpler-logging-2/">LOG_ID</a>([a absoluteURL]);
<a href="http://vgable.com/blog/2008/08/05/simpler-logging-2/">LOG_ID</a>([b absoluteURL]);
</pre>
<blockquote><p>
[a isEqual:b] = 0<br />
[[a absoluteURL] isEqual:[b absoluteURL]] = 1<br />
[a absoluteURL] = http://vgable.com/blog<br />
[b absoluteURL] = http://vgable.com/blog
</p></blockquote>
<p>Remember that <strong>collections use <code>isEqual:</code> to determine equality, so you may have to convert an <code>NSURL</code> to an <code> absoluteURL</code> to get the behavior you expect, especially with <code>NSSet</code> and <code>NSDictionary</code>.</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2009/04/22/nsurl-isequal-gotcha/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To Write Cocoa Object Getters</title>
		<link>http://vgable.com/blog/2009/03/31/how-to-write-cocoa-object-getters/</link>
		<comments>http://vgable.com/blog/2009/03/31/how-to-write-cocoa-object-getters/#comments</comments>
		<pubDate>Tue, 31 Mar 2009 18:51:51 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[MacOSX]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[autorelease]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[NSObject]]></category>
		<category><![CDATA[retain]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/2009/03/31/how-to-write-cocoa-object-getters/</guid>
		<description><![CDATA[Setters are more straightforward than getters, because you don&#8217;t need to worry about memory management. The best practice is to let the compiler write getters for you, by using Declared Properties. But when I have to implement a getter manually, I prefer the (to my knowledge) safest pattern, - (TypeOfX*) x; { &#160;&#160;return [[x retain] [...]]]></description>
			<content:encoded><![CDATA[<p>Setters are more straightforward than <a href="http://vgable.com/blog/2009/03/29/how-to-write-cocoa-object-setters/">getters</a>, because you don&#8217;t <em>need</em> to worry about memory management. </p>
<p>The best practice is to let the compiler write getters for you, by using <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html">Declared Properties</a>.</p>
<p>But when I have to implement a getter manually, I prefer the (to my knowledge) safest pattern,</p>
<pre>- (TypeOfX*) x;
{
&nbsp;&nbsp;return [[x retain] autorelease];
}</pre>
<p>Note that by convention in Objective-C, a getter for the variable <code>jabberwocky</code> is simply called <code>jabberwocky</code>, <em>not</em> <code>getJabberwocky</code>.</p>
<h3>Why <code>retain</code> Then <code>autorelease</code></h3>
<p>Basically <code>return [[x retain] autorelease];</code> <em>guarantees</em> that what the getter returns will be valid for as long as any local objects in the code that called the the getter.</p>
<p>Consider,</p>
<pre>NSString* oldName = [person name];
[person setName:@"Alice"];
NSLog(@"%@ has changed their name to Alice", oldName);</pre>
<p>If <code>-setName:</code> immediately <code>release</code>es the value that <code>-name</code> returned, <code>oldName</code> will be invalid when it&#8217;s used in <code>NSLog</code>.  But if the implementation of <code>[x name]</code> used <code>retain/autorelease</code>, then <code>oldName</code> would still be valid, because it would not be destroyed until the autorelease pool around the <code>NSLog</code> was drained.</p>
<p>Also, autorelease pools are <em>per thread</em>; different threads have different autorelease pools that are drained at different times. <code>retain/autorelease</code> makes sure the object is on the calling thread&#8217;s pool.</p>
<p>If this cursory explanation isn&#8217;t enough, read <a href="http://www.sethwillits.com/blog/?p=24">Seth Willitis&#8217; detailed explanation of <code>retain/autorelease</code></a>. I&#8217;m not going to explain it further here, because he&#8217;s done such a through job of it.</p>
<h3>Ugly</h3>
<p><code>return [[x retain] autorelease];</code> is more complicated, and harder to understand then a simple <code>return x;</code>.  But sometimes that ugliness is necessary, and the best place to hide it is in a one-line getter method. It&#8217;s self documenting. And once you understand Cocoa memory management, it&#8217;s entirely clear what the method does. For me, <strong>the tiny readability cost is worth the safety guarantee</strong>.</p>
<h3>Big</h3>
<p><code>return [[x retain] autorelease];</code> increases peak memory pressure, because it can defer <code>dealloc</code>-ing unused objects  until a few autorelease pools are drained. Honestly I&#8217;ve never measured memory usage, and found this to be a significant problem.  It certainly could be, especially if the thing being returned is a large picture or chunk of data. But in my experience, it&#8217;s nothing to worry about for getters that return typical objects, unless there are measurements saying otherwise.</p>
<h3>Slow</h3>
<p><code>return [[x retain] autorelease];</code> is obviously slower then just <code>return x;</code>. But I doubt that optimizing an O(1) getter is going to make a significant difference to your application&#8217;s performance &#8212; especially compared to other things you could spend that time optimizing.  So until I have data telling me otherwise, I don&#8217;t worry about adding an the extra method calls.</p>
<h3>This is a Good Rule to Break</h3>
<p>As I mentioned before, getters don&#8217;t <em>need</em> to worry about memory management. It could be argued that <strong>the <code>return [[x retain] autorelease];</code> pattern is a <em>premature optimization</em> of <em>theoretical</em> safety at the expense of <em>concrete</em> performance</strong>.</p>
<p>Good programmers try to avoid premature optimization; so perhaps I&#8217;m wrong to follow this &#8220;safer&#8221; pattern. But until I have data showing otherwise, I like to do the safest thing.</p>
<p><strong>How do you write getters, and <em>why</em>?</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2009/03/31/how-to-write-cocoa-object-getters/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>How To Write Cocoa Object Setters</title>
		<link>http://vgable.com/blog/2009/03/29/how-to-write-cocoa-object-setters/</link>
		<comments>http://vgable.com/blog/2009/03/29/how-to-write-cocoa-object-setters/#comments</comments>
		<pubDate>Sun, 29 Mar 2009 19:53:40 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Bug Bite]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[MacOSX]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[autorelease]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Memory Management]]></category>
		<category><![CDATA[NSObject]]></category>
		<category><![CDATA[retain]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/2009/03/29/how-to-write-cocoa-object-setters/</guid>
		<description><![CDATA[There are several ways to write setters for Objective-C/Cocoa objects that work. But here are the practices I follow; to the best of my knowledge they produce the safest code. Principle 0: Don&#8217;t Write a Setter When possible, it&#8217;s best to write immutable objects. Generally they are safer, and easier to optimize, especially when it [...]]]></description>
			<content:encoded><![CDATA[<p>There are several ways to write setters for Objective-C/Cocoa objects that work. But here are the practices I follow; to the best of my knowledge they produce the safest code.</p>
<h3>Principle 0: Don&#8217;t Write a Setter</h3>
<p>When possible, it&#8217;s best to write <a href="http://en.wikipedia.org/wiki/Immutable_object">immutable objects</a>.  Generally they are safer, and easier to optimize, especially when it comes to concurrency.</p>
<p>By definition immutable objects have no setters, so <strong>always ask yourself if you <em>really</em> need a setter</strong>,  before you write one, and whenever revisiting code.</p>
<p>I&#8217;ve removed many of my setters by making the thing they set an argument to the class&#8217;s <code>-initWith:</code> constructor.  For example,</p>
<pre>CustomWidget *widget = [[CustomWidget alloc] init];
[widget setController:self];</pre>
<p>becomes,</p>
<pre>CustomWidget *widget = [[CustomWidget alloc] initWithController:self];</pre>
<p>This is less code, and now, <code>widget</code> is never in a partially-ready state with no controller.</p>
<p>It&#8217;s not always practical to do without setters. If an object looks like it needs a settable property, it probably does. But in my experience, questioning the assumption that a property needs to be changeable pays off  consistently, if infrequently.</p>
<h3>Principle 1: Use <code>@synthesize</code></h3>
<p>This should go without saying, but as long as I&#8217;m enumerating best-practices: if you are using Objective-C 2.0 (iPhone or Mac OS X 10.5 &#038; up) you should <strong>use <code>@synthesize</code>-ed <a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW1">properties</a> to implement your setters.</strong></p>
<p>The obvious benefits are less code, and setters that are guaranteed to work by the compiler.  A less obvious benefit is <a href="http://cocoawithlove.com/2008/08/in-defense-of-objective-c-20-properties.html">a clean, abstracted way to expose the state values of an object</a>.  Also, <a href="http://vgable.com/blog/2008/12/20/automatically-freeing-every-property/">using properties can simplify you <code>dealloc</code> method</a>.</p>
<p>But watch out for the a <a href="http://vgable.com/blog/2009/03/17/mutable-property-and-copy-gotcha/">gotcha if you are using <code>copy</code>-assignment for an <code>NSMutable</code> object</a>!</p>
<p>(Note: Some Cocoa programmers strongly dislike the dot-syntax that was introduced with properties and lets you say <code>x.foo = 3;</code> instead of <code>[x setFoo:3];</code>.  But, <strong>you can use properties without using the dot-syntax</strong>.  For the record, I think the dot syntax is an improvement.  But don&#8217;t let a hatred of it it keep you from using properties.)</p>
<h3>Principle 2: Prefer <code>copy</code> over <code>retain</code></h3>
<p><a href="http://vgable.com/blog/2008/11/14/prefer-copy-over-retain/">I covered this in detail here</a>.  In summary, use <code>copy</code> over <code>retain</code> whenever possible: <strong><code>copy</code> is safer</strong>, and with most basic Foundation objects, <strong><code>copy</code> is just as fast and efficient as <code>retain</code>.</strong></p>
<h3>The Preferred Pattern</h3>
<p>When properties are unavailable, this is my &#8220;go-to&#8221; pattern:</p>
<pre>
- (void) setX:(TypeOfX*)newX;
{
&nbsp;&nbsp;[memberVariableThatHoldsX autorelease];
&nbsp;&nbsp;memberVariableThatHoldsX = [newX copy];
}
</pre>
<p>Sometimes I use use <code>retain</code>, or very rarely <code>mutableCopy</code>, instead of <code>copy</code>. But if <code>autorelease</code> won&#8217;t work, then I use a different pattern. I have a few reasons for writing setters this way.</p>
<h4>Reason: Less Code</h4>
<p>This pattern is only two lines of code, and has <strong>no conditionals</strong>.  There is very little that can I can screw up when writing it. It always does the same thing, which simplifies debugging.</p>
<h4>Reason: <code>autorelease</code> Defers Destruction</h4>
<p>Using <code>autorelease</code> instead of <code>release</code> is just a little bit safer, because it does not immediately destroy the old value.</p>
<p>If the old value is immediately released in the setter then this code will sometimes crash,</p>
<pre>
NSString* oldName = [x name];
[x setName:@"Alice"];
NSLog(@"%@ has changed their name to Alice", oldName);
</pre>
<p>If <code>-setName:</code> immediately releasees the value that <code>-name</code> returned, <code>oldName</code> will be invalid when it&#8217;s used in <code>NSLog</code>.</p>
<p>But if If <code>-setName:</code> <code>autorelease</code>-ed the old value instead, this wouldn&#8217;t be a problem; <code>oldName</code> would still be valid until the current autorelease pool was drained.</p>
<h4>Reason: Precedent</h4>
<p>This is <a href="http://google-styleguide.googlecode.com/svn/trunk/objcguide.xml#Autorelease_Then_Retain">the pattern that google recommends.</a></p>
<blockquote><p>
When assigning a new object to a variable, one must first release the old object to avoid a memory leak. There are several &#8220;correct&#8221; ways to handle this. We&#8217;ve chosen the &#8220;autorelease then retain&#8221; approach because it&#8217;s less prone to error. Be aware in tight loops it can fill up the autorelease pool, and may be slightly less efficient, but we feel the tradeoffs are acceptable.</p>
<pre>- (void)setFoo:(GMFoo *)aFoo {
  [foo_ autorelease];  // Won't dealloc if |foo_| == |aFoo|
  foo_ = [aFoo retain];
}
</pre>
</blockquote>
<h3>Backup Pattern (No <code>autorelease</code>)</h3>
<p>When <code>autorelease</code> won&#8217;t work, my Plan-B is:</p>
<pre>
- (void) setX:(TypeOfX*)newX;
{
&nbsp;&nbsp;id old = memberVariableThatHoldsX;
&nbsp;&nbsp;memberVariableThatHoldsX = [newX copy];
&nbsp;&nbsp;[old release];
}
</pre>
<h4>Reason: Simple</h4>
<p>Again, there are no conditionals in this pattern. There&#8217;s no <code>if(oldX != newX)</code> test for me to screw up. (Yes, I have done this. It wasn&#8217;t a hard bug to discover and fix, but it was a bug nonetheless.) When I&#8217;m debugging a problem, I <em>know</em> exactly what <code>setX:</code> did to it&#8217;s inputs, without having to know what they are.</p>
<h4>On <code>id old</code></h4>
<p>I like naming my temporary old-value <code>id old</code>, because that name &#038; type <em>always</em> works, and it&#8217;s short. It&#8217;s less to type, and less to think about than <code>TypeOfX* oldX</code>.</p>
<p>But I don&#8217;t think it&#8217;s necessarily the best choice for doing more to <code>old</code> than sending it <code>release</code>.</p>
<p>To be honest I&#8217;m still evaluating that naming practice.  But so far I&#8217;ve been happy with it.</p>
<h3>Principle 3: Only Optimize <em>After</em> You Measure</h3>
<p>This is an old maxim of Computer Science, but it bears repeating.</p>
<p>The most common pattern for a setter feels like premature optimization:</p>
<pre>- (void) setX:(TypeOfX*)newX;
{
&nbsp;&nbsp;if(newX != memberVariableThatHoldsX){
&nbsp;&nbsp;&nbsp;&nbsp;[memberVariableThatHoldsX release];
&nbsp;&nbsp;&nbsp;&nbsp;memberVariableThatHoldsX = [newX copy];
&nbsp;&nbsp;}
}
</pre>
<p>Testing <code>if(newX != memberVariableThatHoldsX)</code> can avoid an expensive <code>copy</code>.</p>
<p>But it also slows <em>every</em> call to <code>setX:</code>.  <code>if</code> statements are more code, that takes time to execute.  When the processor <a href="http://en.wikipedia.org/wiki/Branch_prediction">guesses wrong</a> while loading instructions after the branch, <code>if</code>&#8216;s become <a href="http://en.wikipedia.org/wiki/Instruction_pipeline#Complications">quite expensive</a>.</p>
<p>To know what way is faster, you have to measure real-world conditions. Even if a <code>copy</code> is  <em>very</em> slow, the conditional approach isn&#8217;t necessarily faster, unless there is code that sets a property to it&#8217;s current value.  Which is kind of silly really.  How often do you write code like,</p>
<pre>[a setX:x1];
[a setX:x1]; //just to be sure!</pre>
<p>or</p>
<pre>[a setX:[a x]];</pre>
<p>Does that look like code you want to optimize? (Trick question! You don&#8217;t know until you test.)</p>
<h4>Hypocrisy!</h4>
<p>I constantly break Principle 3 by declaring properties in <em>iPhone</em> code as <code>nonatomic</code>, since it&#8217;s the pattern Apple uses in their libraries. I assume Apple has good reason for it; and since I will need to write synchronization-code to safely use <em>their</em> libraries, I figure it&#8217;s not much more work to reuse the same code to protect access to my objects.</p>
<p>I can&#8217;t shake the feeling I&#8217;m wrong to do this.  But it seems more wrong to not follow Apple&#8217;s example; they wrote the iPhone OS in the first place.</p>
<h3>If you know a better best practice, say so!</h3>
<p>There isn&#8217;t a way to write a setter that works optimally <em>all</em> the time, but there is a setter-pattern that works optimally more often then other patterns. With your help I can find it.</p>
<h4>UPDATE 03-30-2009:</h4>
<p> <a href="http://www.wilshipley.com/blog/2005/07/code-insults-mark-i.html">Wil Shiply disagrees</a>.  Essentially his argument is that setters are called a lot, so if they aren&#8217;t aggressive about freeing memory, you can have thousands of dead objects rotting in an autorelease pool. Plus, setters often do things like registering with the undo manager, and that&#8217;s expensive, so it&#8217;s a good idea to have conditional code that only does that when necessary.</p>
<p>My rebuttal is that you should optimize big programs by draining autorelease pools early anyway; and that mitigates the dead-object problem.</p>
<p>With complex setters I can see why it makes sense to check if you <em>need</em> to do something before doing it. I still prefer safer, unconditional, code as a <em>simple first implementation</em>. That&#8217;s why it&#8217;s my go-to pattern. But if most setters you write end up being more complex, it might be the wrong pattern.</p>
<p>Really you should <a href="http://www.wilshipley.com/blog/2005/07/code-insults-mark-i.html">read what Wil says</a>, and decide for yourself. He&#8217;s got much more experience with Objective-C development then I do.</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2009/03/29/how-to-write-cocoa-object-setters/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

