<?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>Jeff Kelley’s Blog &#187; Cocoa</title>
	<atom:link href="http://blog.slaunchaman.com/tag/cocoa/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.slaunchaman.com</link>
	<description>Mac tips, iPhone applications, and the like</description>
	<lastBuildDate>Fri, 02 Dec 2011 04:51:07 +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>Autorelease is Not Your Friend</title>
		<link>http://blog.slaunchaman.com/2010/11/16/autorelease-is-not-your-friend/</link>
		<comments>http://blog.slaunchaman.com/2010/11/16/autorelease-is-not-your-friend/#comments</comments>
		<pubDate>Tue, 16 Nov 2010 05:00:15 +0000</pubDate>
		<dc:creator>Jeff Kelley</dc:creator>
				<category><![CDATA[Programming Tips]]></category>
		<category><![CDATA[Apple]]></category>
		<category><![CDATA[autorelease]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[NSAutoreleasePool]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.slaunchaman.com/?p=334</guid>
		<description><![CDATA[How many times have you written this line? NSMutableArray *foo = [[[NSMutableArray alloc] init] autorelease]; At first glance, it looks fine. foo is an autoreleased NSMutableArray that you can use and, at the end of the method, it’s gone into the ether of the autorelease pool. Don’t get me wrong, most of the time, this [...]]]></description>
			<content:encoded><![CDATA[<p>How many times have you written this line?</p>
<blockquote><p><code>NSMutableArray *foo = [[[NSMutableArray alloc] init] autorelease];</code></p></blockquote>
<p>At first glance, it looks fine. <code>foo</code> is an autoreleased <code>NSMutableArray</code> that you can use and, at the end of the method, it’s gone into the ether of the autorelease pool. Don’t get me wrong, <em>most of the time</em>, this use of <code>-autorelease</code> is acceptable. But, in this post, I’ll try to convince you to use autorelease differently in subtle ways.<span id="more-334"></span></p>
<h3>Avoid Enormous Pools</h3>
<p>Back to the first line of code. Let’s look at a real-world example of using <code>-autorelease</code> this way:</p>
<blockquote><p><code>
<pre>- (void)doSomeStuffWithAHugeArray:(NSArray *)array
{
    for (NSUInteger i = 0; i &lt; [array count]; i++) {
        NSDictionary *aDict = (NSDictionary *)[array objectAtIndex:i];

        NSMutableArray *foo = [[[NSMutableArray alloc] init] autorelease];
        [foo addObject:[aDict objectForKey:@"someKey"]];

        // Some general processing of foo here.
    }
}</pre>
<p></code></p></blockquote>
<p>To the programmer, this appears perfectly valid. <code>foo</code> will be created once for each object in <code>array</code> and some processing will occur on it. You don’t need to worry about memory management since it’s autoreleased, right?</p>
<p>Right?</p>
<p>But what happens if there are 4 million items in this array? And you’re running on an iPhone? See, the problem with autorelease pools is that they drain their contents at some future point in the run loop. During your methods’ stack frame, the app never returns to the run loop. These objects keep getting added to the autorelease pool, and until the method is done, they don’t go anywhere. On the Mac this isn’t as much of an issue, since unused objects will get paged out of active memory, but on iOS, your app will be terminated when you run out of memory.</p>
<p>What to do? There are two approaches: first, implement a counter:</p>
<blockquote><p><code>
<pre>NSAutoreleasePool *pool = nil;
NSUInteger count = 0;

for (NSUInteger i = 0; i &lt; [array count]; i++) {
    if (pool == nil) {
        pool = [[NSAutoreleasePool alloc] init];
    }

    static NSUInteger count = 0;
    NSDictionary *aDict = (NSDictionary *)[array objectAtIndex:i];

    NSMutableArray *foo = [[[NSMutableArray alloc] init] autorelease];
    [foo addObject:[aDict objectForKey:@"someKey"]];

    // Some general processing of foo here.

    count++;
    if (count % 1000 == 0) {
        // count is a multiple of 1,000
        [pool drain];
        pool = nil;
    }
}
[pool drain];</pre>
<p></code></p></blockquote>
<p>What have we gained, aside from a lot more code? Every 1,000 iterations through this loop, the autorelease pool that we’ve created drains its contents; this eliminates the possibility of millions of <code>NSMutableArray</code>s littering the contents of memory. In this case it’s unnecessary as we could just release <code>foo</code> at the end of the loop, but in most cases you’ll be dealing with other methods, either your own or those provided by Cocoa Touch or some library, that return autoreleased objects. This method prevents those objects from gumming up the works too much. As an example, if you’re processing JSON—let’s say Reddit comments—you can easily get millions of autoreleased <code>NSString</code> objects created, and significant processing of them can become unwieldy.</p>
<h3>Treat <code>-autorelease</code> like <code>-release</code></h3>
<p>Here’s another typical pattern you see in Objective-C code:</p>
<blockquote><p><code>
<pre>MyAwesomeObject *bar = [[[MyAwesomeObject alloc] init] autorelease];
[NSThread detachNewThreadSelector:@selector(extraLongComputation:)
                         toTarget:self
                       withObject:bar];
bar.someProperty = 42;</pre>
<p></code></p></blockquote>
<p>That looks OK at first, but depending on how your app is running, you could be adding <code>bar</code> to an autorelease pool that is drained while <code>-extraLongComputation</code> is running. If you’re performing selectors after a delay or using an <code>NSTimer</code>, this is especially likely. In this case, I like to treat <code>-autorelease</code> like <code>-release</code>:</p>
<blockquote><p><code>
<pre>MyAwesomeObject *bar = [[MyAwesomeObject alloc] init];
[NSThread detachNewThreadSelector:@selector(extraLongComputation:)
                         toTarget:self
                       withObject:bar];
bar.someProperty = 42;
[bar autorelease];</pre>
<p></code></p></blockquote>
<p>By itself, this isn’t sufficient. However, when coupled with this code:</p>
<blockquote><p><code>
<pre>- (void)extraLongComputation:(MyAwesomeObject *)obj
{
    [obj retain];

    // TODO: write computation code.

    [obj release];
}</pre>
<p></code></p></blockquote>
<p>This ensures that <code>bar</code> survives long enough for your computation.</p>
<p>Nothing I’ve written here is a panacea, and I’m sure it’s all been written before (and probably better), but my hope is to at least encourage you to think more about the memory management of your application, lest you find yourself debugging odd crashes the night before a deadline.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.slaunchaman.com/2010/11/16/autorelease-is-not-your-friend/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Quick Tip: Don&#8217;t Do This</title>
		<link>http://blog.slaunchaman.com/2010/05/10/quick-tip-dont-do-this/</link>
		<comments>http://blog.slaunchaman.com/2010/05/10/quick-tip-dont-do-this/#comments</comments>
		<pubDate>Tue, 11 May 2010 04:01:44 +0000</pubDate>
		<dc:creator>Jeff Kelley</dc:creator>
				<category><![CDATA[Programming Tips]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[gotchas]]></category>
		<category><![CDATA[NSObject]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Objective-C Runtime]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://blog.slaunchaman.com/?p=263</guid>
		<description><![CDATA[I could not find out where a bug was coming from for the life of me today. Naturally it one of those &#8220;assignment instead of equality&#8221; bugs that seem to crop up when trying to code too quickly. The difference here was that I had implemented a subclass of NSObject that reimplemented the method +resolveInstanceMethod:. [...]]]></description>
			<content:encoded><![CDATA[<p>I could <em>not</em> find out where a bug was coming from for the life of me today. Naturally it one of those &ldquo;assignment instead of equality&rdquo; bugs that seem to crop up when trying to code too quickly. The difference here was that I had implemented a subclass of <code>NSObject</code> that reimplemented the method <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/doc/uid/20000050-SW5"><code>+resolveInstanceMethod:</code></a>. So, the code went like this:<code>
<pre>+ ( BOOL )resolveInstanceMethod:( SEL )sel
{
    if ( sel = @selector( setFoobar: )) {
        return class_addMethod([ self class ], sel, ( IMP )setFB, "v@:@" );
    } else if ( sel = @selector( foobar )) {
        return class_addMethod([ self class ], sel, ( IMP )getFB, "@@:" );
    } else {
        return [ super resolveInstanceMethod:sel ];
    }
}</pre>
<p></code><br />
For those of you keeping score at home, when the Objective-C runtime tried to resolve <em>any</em> selector, this method happily added a selector for <code>-setFoobar:</code> to <code>self</code>&rsquo;s class and returned <code>YES</code>.</p>
<p>Don&rsquo;t do this.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.slaunchaman.com/2010/05/10/quick-tip-dont-do-this/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cocoa Tutorial: Strip Non-Alphanumeric Characters from an NSString</title>
		<link>http://blog.slaunchaman.com/2009/11/01/cocoa-tutorial-strip-non-alphanumeric-characters-from-an-nsstring/</link>
		<comments>http://blog.slaunchaman.com/2009/11/01/cocoa-tutorial-strip-non-alphanumeric-characters-from-an-nsstring/#comments</comments>
		<pubDate>Sun, 01 Nov 2009 16:36:46 +0000</pubDate>
		<dc:creator>Jeff Kelley</dc:creator>
				<category><![CDATA[Programming Tips]]></category>
		<category><![CDATA[Apple]]></category>
		<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Cocoa Touch]]></category>
		<category><![CDATA[convenience]]></category>
		<category><![CDATA[NSCharacterSet]]></category>
		<category><![CDATA[NSString]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://blog.slaunchaman.com/?p=192</guid>
		<description><![CDATA[Let’s say you have an NSString that contains both alphanumeric and non-alphanumeric characters and you want to strip the non-alphanumeric characters out of it. The hard way is to manually go through, character-by-character, and put the character in a new string if it matches certain criteria. But why do it the hard way? Apple provides [...]]]></description>
			<content:encoded><![CDATA[<p>Let’s say you have an NSString that contains both alphanumeric and non-alphanumeric characters and you want to strip the non-alphanumeric characters out of it. The hard way is to manually go through, character-by-character, and put the character in a new string if it matches certain criteria. But why do it the hard way?</p>
<p>Apple provides a class that we can use for this to great effect: <a title="NSCharacterSet Class Reference" href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSCharacterSet_Class/Reference/Reference.html"><code>NSCharacterSet</code></a>. We want alphanumeric characters, so we can create a character set of the characters we want using this method:</p>
<blockquote><p><code>NSCharacterSet *alphanumericSet = [ NSCharacterSet alphanumericCharacterSet ];</code></p></blockquote>
<p>Now we have a character set like we want. We just need a way to turn our string into a string that contains only those characters. Unfortunately, the closest thing in <code>NSString</code>’s implementation is the <code>-stringByTrimmingCharactersInSet:</code> method. But that seems to do the <em>opposite</em> of what we want. Fortunately <code>NSCharacterSet</code> has our back here. We can use the <code>-invertedSet</code> method. So here is our final code:</p>
<blockquote><p><code>NSString *beginningString = @"Some string with non-alphanumeric characters. !@#$%^&amp;*()";<br />
NSCharacterSet *nonalphanumericSet = [[ NSCharacterSet alphanumericCharacterSet ] invertedSet ];<br />
NSString *endingString = [ beginningString stringByTrimmingCharactersInSet:nonalphanumericSet ];</code></p></blockquote>
<p>In this example, <code>endingString</code> will be equal to “Somestringwithnonalphanumericcharacters”.</p>
<p><strong>UPDATE:</strong> As it turns out, this only works if the non-alphanumeric characters are at the beginning or end of the <code>NSString</code>. Whoops.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.slaunchaman.com/2009/11/01/cocoa-tutorial-strip-non-alphanumeric-characters-from-an-nsstring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

