<?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; NSObject</title>
	<atom:link href="http://vgable.com/blog/tag/nsobject/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>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>7</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>
		<item>
		<title>-description, Little-Known Hero of Debugging</title>
		<link>http://vgable.com/blog/2008/09/16/description-little-known-hero-of-debugging/</link>
		<comments>http://vgable.com/blog/2008/09/16/description-little-known-hero-of-debugging/#comments</comments>
		<pubDate>Wed, 17 Sep 2008 00:50:33 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[MacOSX]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Sample Code]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[NSLog]]></category>
		<category><![CDATA[NSObject]]></category>
		<category><![CDATA[NSString]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/2008/09/16/description-little-known-hero-of-debugging/</guid>
		<description><![CDATA[Or: How to Make NSLog() Useful With Your Objects Say you have an archaically named NSArray that you want to inspect &#8212; it&#8217;s easy to do, since NSLog(@"The bestiary is %@", bestiary); prints out the array&#8217;s contents 2008-09-16 19:46:06.445 Tester[2678:10b] The bestiary is ( Cheetah, Pumpa, Jaguar, Panther, Tiger, Leopard ) But if you try [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Or: How to Make <code>NSLog()</code> Useful With Your Objects</strong></p>
<p>Say you have an archaically named <code>NSArray</code> that you want to inspect &#8212; it&#8217;s easy to do, since <code>NSLog(@"The bestiary is %@", bestiary);</code> prints out the array&#8217;s contents</p>
<blockquote><p>2008-09-16 19:46:06.445 Tester[2678:10b] The bestiary is (<br />
    Cheetah,<br />
    Pumpa,<br />
    Jaguar,<br />
    Panther,<br />
    Tiger,<br />
    Leopard<br />
)
</p></blockquote>
<p>But if you try to <code>NSLog</code> your own object, you get pretty useless output, like<br />
<blockquote>myObject = &lt;MyObject: 0x53f330&gt;</p></blockquote>
<p>Fortunately, it&#8217;s easy to fix!  Just implement the method <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/description"><code>-(NSString*) description;</code></a> and whatever it returns will be printed by <code>NSLog</code> and GDB (<code>po <em>object</em></code>, will print <em>object</em> in GDB and the Xcode debugging console).</p>
<p>Here&#8217;s an (unfortunately complex) example,<br />
<br /><code>- (NSString*) description;<br />
{<br />
&nbsp;&nbsp;return [NSString stringWithFormat:@"<%@ %p> = {\n\tquestion=%@,\n\tanswer=%@,\n\tsource=%@\n}", [self className], self, self.question, self.answer, self.source];<br />
}<br /></code><br />
output:</p>
<blockquote><p>myObject = &lt;MyObject 0x53eed0&gt; = {<br />
&nbsp;&nbsp;question=What is the Best Thing Ever Of All Times, Ever?,<br />
&nbsp;&nbsp;answer=The Internet!,<br />
&nbsp;&nbsp;source=http://www.cabel.name/2008/01/2007-cabel-yay-awards.html<br />
}</p></blockquote>
<p><strong>Useful Formatters and such</strong></p>
<p><a href="http://vgable.com/blog/2008/08/05/simpler-logging-2/">These macros have made my debugging-life easer</a>.</p>
<p><code>%p</code> tells <code>NSLog</code> to print the address of a pointer.</p>
<p><code>-className</code> returns gives the name of a class as an <code>NSString</code>.</p>
<p><em>Don&#8217;t manually print out a Cocoa <code>struct</code>, ever</em>, there are already <code>NSStringTo*</code> functions to do that for you, like <code>NSStringFromPoint()</code>.</p>
<p><code>NSStringFromSelector()</code> works as advertized (and paired with <code>NSSelectorFromString()</code> is very useful in general).</p>
<p><code>%lld</code> tells <code>NSLog</code> to print a <code>long long</code> (64-bit integer).  See also, <a href="http://www.cplusplus.com/reference/clibrary/cstdio/printf.html"><code>printf</code> reference</a>.</p>
<p><code>%Lf</code> tells <code>NSLog</code> to print a <code>long double</code>. See also, <a href="http://www.cplusplus.com/reference/clibrary/cstdio/printf.html"><code>printf</code> reference</a>.</p>
<p><strong>Best Practices</strong></p>
<p>Whenever you make a new object, I <em>strongly</em> recommended immediately implementing a <code>description</code> method, and religiously keeping it up to date (it&#8217;s not hard, honest!).  This won&#8217;t fix bugs, but it will make finding some of them <em>much easier</em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2008/09/16/description-little-known-hero-of-debugging/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

