<?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; Cocoa</title>
	<atom:link href="http://vgable.com/blog/category/programming/objective-c/cocoa/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>#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>NSDictionary Copies It&#8217;s Keys</title>
		<link>http://vgable.com/blog/2010/07/08/nsdictionary-copies-its-keys/</link>
		<comments>http://vgable.com/blog/2010/07/08/nsdictionary-copies-its-keys/#comments</comments>
		<pubDate>Thu, 08 Jul 2010 17:55:29 +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[Apple]]></category>
		<category><![CDATA[copy]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[NSDictionary]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=643</guid>
		<description><![CDATA[An NSDictionary will retain it&#8217;s objects, and copy it&#8217;s keys. Here are some effects this has had on code I&#8217;ve worked on. Sometimes you get the same object you put in, sometimes not. Immutable objects are optimized to return themselves as a copy. (But with some exceptions!). So the following code: NSDictionary *d = [NSDictionary [...]]]></description>
			<content:encoded><![CDATA[<p>An <code>NSDictionary</code> will <code>retain</code> it&#8217;s objects, and <code>copy</code> it&#8217;s keys. </p>
<p>Here are some effects this has had on code I&#8217;ve worked on.</p>
<ul>
<li>
<strong>Sometimes you get the same object you put in, sometimes not</strong>.<br />
<a href="http://vgable.com/blog/2008/11/14/prefer-copy-over-retain/">Immutable objects are optimized to return themselves as a <code>copy</code></a>. (But with some exceptions!). So the following code:</p>
<pre>
	NSDictionary *d = [NSDictionary dictionaryWithObject:@"object" forKey:originalKey];
	for(id aKey in d)
		if(aKey == originalKey)
			NSLog(@"Found the original key!");
</pre>
<p>Might print &#8220;Found the original key!&#8221;, and might not, depending on how <code>[originalKey  copy]</code> is implemented. For this reason, <strong>never use pointer-equality when comparing keys</strong>.</p>
<li><strong>Mutable objects make bad keys</strong>. If <code>x</code> is a mutable <code>NSObject</code>, <code>[x copy] is an </code><em>immutable</em> copy of <code>x</code>, <em>at that point in time</em>. Any changes to <code>x</code> are <em>not</em> reflected in the copy. For example,
<pre>
	[dict setObject:x forKey:key];
	//...code that changes key, but not dict
	<a href="http://vgable.com/blog/2008/12/04/nsassert-considered-harmful/">assert</a>([[dict objectForKey:key] isEqual:x]); //fails!
</pre>
<p>Because the <code>copy</code> is an immutable object, it will blow up if you try to mutate it.</p>
<pre>
	NSMutableString *key = //something...
	[dict setObject:x forKey:key];
	for(NSMutableString *aKey in dict)
		[aKey appendString:@"2"]; //Error, aKey isn't mutable, even though key is!
</pre>
</li>
<li>
<strong>View objects make bad keys</strong>. Views have state related to  the screen: their <code>frame</code>, position in the view hierarchy, animation layers, etc. When you <code>copy</code> a view object, the copy won&#8217;t (always) be <code>isEqual:</code> to the original, because it&#8217;s not on the screen in exactly the same way.
</li>
</li>
<li>
<strong>Your classes must support <code>NSCopying</code> to be used as a key in an <code>NSDictionary</code></strong>, you can&#8217;t just <a href="http://mikeash.com/pyblog/friday-qa-2010-06-18-implementing-equality-and-hashing.html">implement <code>-hash</code> and <code>-isEqual:</code></a> in your custom classes.
</li>
</ul>
<p>Of course, this isn&#8217;t a complete list of every way key-copying can trip you up. But if you understand what <code>copy</code> means in Cocoa, and remember how <code>NSDictionary</code> works, you&#8217;ll be able to avoid or quickly solve any issues.</p>
<h3>How to Document Such Behavior Better Than Apple Did</h3>
<p>Given what we know about <code>NSDictionary</code>, what&#8217;s wrong with the following snippit from <code>NSDictionary.h</code>?</p>
<pre>
@interface NSMutableDictionary : NSDictionary
- (void)setObject:(id)anObject forKey:(id)aKey;
@end
</pre>
<p>Answer: <code> aKey </code> needs to implement <code>NSCopying</code>, so it should be of type <code>(id&lt;NSCopying&gt;)</code> instead of type <code>(id)</code>. That way, the header is self-documenting, and, if like most smart programmers, you&#8217;re using autocomplete to type out Cocoa&#8217;s long method names, the auto-completed template will be self-documenting too.</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2010/07/08/nsdictionary-copies-its-keys/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Ask F-Script!</title>
		<link>http://vgable.com/blog/2010/06/14/ask-f-script/</link>
		<comments>http://vgable.com/blog/2010/06/14/ask-f-script/#comments</comments>
		<pubDate>Mon, 14 Jun 2010 06:11:04 +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[Command-Line]]></category>
		<category><![CDATA[F-Script]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[MacRuby]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[REPL]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=622</guid>
		<description><![CDATA[F-Script is an amazingly useful tool for answering quick API questions, like &#8220;What happens if I pass in nil&#8220;. I use it several times a week. For verifying corner-cases, F-Script is faster than google, stackoverflow, or reading header files. Just type in a questionable expression and instantly see what happens. There&#8217;s a good tutorial to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.fscript.org/">F-Script</a> is an amazingly useful tool for answering quick API<br />
questions, like &#8220;What happens if I pass in <code>nil</code>&#8220;. I use it several times a week. For verifying corner-cases, F-Script is faster than google, stackoverflow, or reading header files. Just type in a questionable expression and <em>instantly</em> see what happens.</p>
<p>There&#8217;s a <a href="http://www.fscript.org/documentation/LearnFScriptIn20Minutes/index.htm">good tutorial</a> to get you started quickly. I&#8217;m not going to reproduce it here, so if any of these examples aren&#8217;t clear, <a href="http://www.fscript.org/documentation/LearnFScriptIn20Minutes/index.htm">go read it</a>.</p>
<h3>Example: <code>NSMutableArray</code></h3>
<p>Objective-C had historically poor support for exceptions, and the Foundation/Cocoa libraries are pretty inconsistent about using them. For example, trying to add <code>nil</code> to an array throws an exception, but trying to remove <code>nil</code> from an array has no effect. Here&#8217;s how I used F-Script to verify that,</p>
<pre>
> a := NSMutableArray array

> a <span style="color:white;background-color:black;">addObject:nil</span>
NSInvalidArgumentException: *** -[NSCFArray insertObject:atIndex:]: attempt to insert nil

> a addObject:'foo'

> a
NSCFArray {'foo'}

> a removeObject:nil

> a
NSCFArray {'foo'}
</pre>
<p>If you&#8217;re not impressed, I understand. Static text really can&#8217;t convey the power of an interactive console. Sure, the F-Script syntax is marginally more concise than writing the equivalent code in Objective-C, but not enough that it matters. What matters is the interactivity, <em>I got my answer as soon as I hit return</em>. No <a href="http://xkcd.com/303/">waiting on the compiler</a>. No switching between the program and Xcode. Immediate feedback.</p>
<p>You might prefer to <a href="http://www.mikeash.com/pyblog/friday-qa-2009-11-20-probing-cocoa-with-pyobjc.html">use python</a> as a Cocoa console. That&#8217;s cool! I prefer F-Script because it&#8217;s closer to Objective-C, but any tool with a <a href="http://en.wikipedia.org/wiki/Read-eval-print_loop">REPL</a> console works. If you have a favorite, please <strong>leave a comment</strong>!</p>
<p>REPL consoles for exploring Objective-C on a Mac:</p>
<ul>
<li><a href="http://www.fscript.org/">F-Script</a></li>
<li><a href="http://www.macruby.org/">MacRuby</a></li>
<li><a href="http://www.mikeash.com/pyblog/friday-qa-2009-11-20-probing-cocoa-with-pyobjc.html"> python</a></li>
<ul>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2010/06/14/ask-f-script/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>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>Never Name a Variable &#8220;Index&#8221;</title>
		<link>http://vgable.com/blog/2010/05/24/never-name-a-variable-index/</link>
		<comments>http://vgable.com/blog/2010/05/24/never-name-a-variable-index/#comments</comments>
		<pubDate>Mon, 24 May 2010 05:31:42 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Bug Bite]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Names]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=603</guid>
		<description><![CDATA[Never name a variable index, especially in C. Instead say what it indexes. For example, if it is used to index an array of Foo objects, call it fooArrayIndex, or currentFooIndex. If the index variable is just used to enumerate over a collection of objects, (eg. for(int i = 0; i &#038;lt arraySize; i++){…} ) [...]]]></description>
			<content:encoded><![CDATA[<p><strong><em>Never</em> name a variable <code>index</code></strong>, especially in C.</p>
<p>Instead <strong>say <em>what</em> it indexes</strong>. For example, if it is used to index an array of <code>Foo</code> objects, call it <code>fooArrayIndex</code>, or <code>currentFooIndex</code>.</p>
<p>If the index variable is just used to enumerate over a collection of objects, (eg. <code>for(int i = 0; i &#038;lt arraySize; i++){…} </code>) then <a href="http://vgable.com/blog/2008/04/07/foreach-for-the-win/">iterate smarter</a>, using a simpler construct that doesn&#8217;t require declaring auxiliary variables. (Eg., in Objective-C use <a href="http://developer.apple.com/mac/library/documentation/cocoa/conceptual/objectivec/articles/ocfastenumeration.html">Fast Enumeration</a>). It&#8217;s not always possible to do this, but it&#8217;s always a good idea to try.<sup>1</sup></p>
<h3>Why <code>index</code> is Especially Bad in C</h3>
<p>The standard <code>strings.h</code> header declares a function named <code>index</code>, that finds the first occurrence of a charicter in a C-string. In practical terms <strong>every C program will have the <code>index</code> function declared everywhere</strong>.</p>
<p>But when a variable is declared with the name <code>index</code> it <a href="http://leepoint.net/notes-java/data/variables/60shadow-variables.html">shadows</a> the function &#8211; meaning the local variable named <code>index</code> takes over the name <code>index</code>, so the function can&#8217;t be called anymore:</p>
<pre>
char * world = index("Hello, World", 'W');
NSLog(@"'%s'", world);
</pre>
<p>Prints &#8220;&#8216;World&#8217;&#8221;, but</p>
<pre>
int index = 0;
char * world = index("Hello, World", 'W');
NSLog(@"'%s'", world);
</pre>
<p>Won&#8217;t compile, because an <code>int</code> isn&#8217;t a function.</p>
<p>Obviously this is a problem for code that uses the <code>index()</code> function — but honestly modern code probably uses a safer, <a href="http://www.mikeash.com/pyblog/friday-qa-2010-02-19-character-encodings.html">unicode-aware</a> string parsing function instead. What&#8217;s given me the most trouble is that <strong>shadowing <code>index</code> makes the compiler give lots of bogus warnings, if you have the useful <code>GCC_WARN_SHADOW</code> <a href="http://vgable.com/blog/2009/12/09/compile-safer/">warning turned on</a></strong>.</p>
<p>There are other good reasons as, specific to Objective-C, which <a href="http://boredzo.org/blog/archives/2009-11-05/the-peril-of-the-index-function">Peter Hosey covers</a>.</p>
<p><sup>1</sup><small>If you <em>really</em> can&#8217;t think of a better name than &#8220;index&#8221;, I prefer the more terse <code>i</code>. It sucks, but at least it&#8217;s shorter. Brevity is a virtue.</small></p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2010/05/24/never-name-a-variable-index/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>What Am I About To Call?</title>
		<link>http://vgable.com/blog/2010/04/29/what-am-i-about-to-call/</link>
		<comments>http://vgable.com/blog/2010/04/29/what-am-i-about-to-call/#comments</comments>
		<pubDate>Fri, 30 Apr 2010 02:40:10 +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[Reverse Engineering]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[gdb]]></category>
		<category><![CDATA[x86]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=597</guid>
		<description><![CDATA[Say you&#8217;re in gdb, and about to execute a call instruction for dyld_stub_objc_msgSend, how do you know what&#8217;s about to happen? On i386 (gdb) x/s *(SEL*)($esp+4) tells you the message that&#8217;s about to be sent. (gdb) po *(id*)$esp tells you the target object that&#8217;s about to get the message.]]></description>
			<content:encoded><![CDATA[<p>Say you&#8217;re in gdb, and about to execute a <code>call</code> instruction for <code>dyld_stub_objc_msgSend</code>, how do you know what&#8217;s about to happen?</p>
<h3>On i386</h3>
<pre>(gdb) x/s *(SEL*)($esp+4)</pre>
<p>tells you the <strong>message</strong> that&#8217;s about to be sent.</p>
<pre>(gdb) po *(id*)$esp</pre>
<p>tells you the <strong>target</strong> object that&#8217;s about to get the message.</p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2010/04/29/what-am-i-about-to-call/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cocoa Influenced The Gang of Four</title>
		<link>http://vgable.com/blog/2010/03/23/cocoa-influenced-the-gang-of-four/</link>
		<comments>http://vgable.com/blog/2010/03/23/cocoa-influenced-the-gang-of-four/#comments</comments>
		<pubDate>Wed, 24 Mar 2010 02:41:36 +0000</pubDate>
		<dc:creator>Vincent Gable</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Quotes]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[NeXT]]></category>

		<guid isPermaLink="false">http://vgable.com/blog/?p=581</guid>
		<description><![CDATA[Next time you want to gloat about how seminal Cocoa is, Erich Gamma: Yes, and it is funny that you mention the iPhone. The iPhone SDK is based on the NeXTStep object-oriented frameworks like the AppKit. It already existed when we wrote Design Patterns 15 years ago and was one source of inspiration. We actually [...]]]></description>
			<content:encoded><![CDATA[<p>Next time you want to gloat about how seminal Cocoa is,</p>
<blockquote><p> <a href="http://en.wikipedia.org/wiki/Erich_Gamma"><strong>Erich Gamma</strong></a>: Yes, and it is funny that you mention the iPhone. The iPhone SDK is based on the NeXTStep object-oriented frameworks like the AppKit. It already existed when we wrote <a href="http://www.amazon.com/gp/product/0201633612?ie=UTF8&#038;tag=vincgabl-20&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=0201633612"><cite>Design Patterns</cite></a> 15 years ago and was one source of inspiration. We actually refer to this framework in several of our patterns: <a href="http://c2.com/cgi/wiki?AdapterPattern">Adapter</a>, <a href="http://c2.com/cgi/wiki?BridgePattern">Bridge</a>, <a href="http://c2.com/cgi/wiki?ProxyPattern">Proxy</a>, and <a href="http://c2.com/cgi/wiki?ChainOfResponsibilityPattern">Chain of Responsibility</a>.</p>
<p><strong>Richard</strong>: Which is a great example of the enduring nature of good design, and how it survives different technical manifestations.</p>
<p>&#8230;</p>
<p><strong>Erich</strong>: Just as an aside, it is also easy to forget that we wrote design patterns before there was Java or C#.
</p></blockquote>
<p>Source: <a href="http://www.informit.com/articles/printerfriendly.aspx?p=1404056"><cite>Design Patterns 15 Years Later: An Interview with Erich Gamma, Richard Helm, and Ralph Johnson</cite></a></p>
]]></content:encoded>
			<wfw:commentRss>http://vgable.com/blog/2010/03/23/cocoa-influenced-the-gang-of-four/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

