<?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>Fiery Robot! &#187; Programming</title>
	<atom:link href="http://www.fieryrobot.com/blog/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.fieryrobot.com/blog</link>
	<description>Defender of Corporate Headquarters</description>
	<lastBuildDate>Mon, 12 Jul 2010 21:26:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>A Watchdog Timer in GCD</title>
		<link>http://www.fieryrobot.com/blog/2010/07/10/a-watchdog-timer-in-gcd/</link>
		<comments>http://www.fieryrobot.com/blog/2010/07/10/a-watchdog-timer-in-gcd/#comments</comments>
		<pubDate>Sat, 10 Jul 2010 21:31:13 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[asynchronous]]></category>
		<category><![CDATA[dispatch source]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[grand central dispatch]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[ipad]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[timer]]></category>
		<category><![CDATA[watchdog]]></category>

		<guid isPermaLink="false">http://www.fieryrobot.com/blog/?p=277</guid>
		<description><![CDATA[A good way to help track down performance issues is through the use of a watchdog timer. They help you by pointing out the places in your code that are taking longer than they should. When the watchdog fires, it can do whatever action is appropriate for your application. I&#8217;m sure all iOS developers are [...]]]></description>
			<content:encoded><![CDATA[<p>A good way to help track down performance issues is through the use of a <em>watchdog timer</em>. They help you by pointing out the places in your code that are taking longer than they should. When the watchdog fires, it can do whatever action is appropriate for your application. I&#8217;m sure all iOS developers are aware of the more extreme watchdog timer that has existed since the beginning of iOS which would kill your application if it took too long to shut down. Our watchdog example will be far more benign <img src='http://www.fieryrobot.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> . <span id="more-277"></span></p>

<p>We&#8217;ll approach this by giving you an object you can create before some critical section and release after it&#8217;s over. You&#8217;ll use it like so:</p>

<pre><code>MyWatchdogTimer *timer = [[MyWatchdogTimer alloc] initWithTimeout:2.0];

// some piece of code that might take a while, but should never take
// more than 2 seconds.
[self myPotentiallyLengthyTask]

[timer invalidate];
[timer release];
</code></pre>

<p>If the timer fires, you know the operation took too long. If it didn&#8217;t all is well, you release it and we&#8217;re done.</p>

<h2>The Class</h2>

<p>The object class is pretty simple:</p>

<pre><code>@interface MyWatchdogTimer {
@private
    dispatch_source_t     _timer;
}

- (id)initWithTimeout:(NSTimeInterval)timeout;
- (void)invalidate;

@end
</code></pre>

<p>As you can see, we&#8217;re merely storing our dispatch source we&#8217;ll be using as a timer.</p>

<p>When doing asynchronous tasks, it&#8217;s very common to use an invalidation idiom for shutting the task down. This pattern can be seen in run loop sources, as well as GCD itself (<code>dispatch&#95;cancel</code>). This ensures the task will be torn down at a time that is appropriate, i.e. it can shut down cleanly.</p>

<h2>The Implementation</h2>

<pre><code>@implementation MyWatchdogTimer

- (id)initWithTimeout:(NSTimeInterval)timeout {
    self = [super init];
    if (self) {            
        dispatch_queue_t queue = dispatch_get_global_queue(
                                    DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

        // create our timer source
        _timer = dispatch_source_create(
                           DISPATCH_SOURCE_TYPE_TIMER, 0, 0,
                           queue);

        // set the time to fire (we're only going to fire once,
        // so just fill in the initial time).
        dispatch_source_set_timer(_timer,
               dispatch_time(DISPATCH_TIME_NOW, timeout * NSEC_PER_SEC),
               DISPATCH_TIME_FOREVER, 0);

        // Hey, let's actually do something when the timer fires!
        dispatch_source_set_event_handler(_timer, ^{
            NSLog(@"WATCHDOG: task took longer than %f seconds",
                    timeout);
            // ensure we never fire again
            dispatch_source_cancel(_timer);
        });

        // now that our timer is all set to go, start it
        dispatch_resume(_timer);
    }
    return self;
}

- (void)dealloc {
    dispatch_source_cancel(_timer);
    dispatch_release(_timer);
    [super dealloc];
}

- (void)invalidate {
    _dispatch_source_cancel(_timer);
}

@end
</code></pre>

<p>That&#8217;s it. Let&#8217;s go over what we&#8217;re doing here.</p>

<p>Our strategy is to install the timer onto a concurrent queue. We want it to run at the same time as our current thread, no? So we get a reference to the standard priority concurrent queue.</p>

<p>Then we create our timer source, using <code>dispatch&#95;source&#95;create</code>. In this case, we&#8217;re creating a timer (there are a few different source types), so we pass <code>DISPATCH&#95;SOURCE&#95;TYPE&#95;TIMER</code> as the first parameter. The other parameters are unused for timers.</p>

<p>Now that we have the timer, we need to set the start time. It&#8217;s specified in nanoseconds, so we need to take our input time and multiply it accordingly. We use <code>dispatch&#95;time</code> so that we can specify a time from now. The third parameter is the interval, but since we&#8217;re only going to fire it once, we just set it to forever. You can also use 0 since we explicitly cancel it when we fire.</p>

<p>Next, we set our event handler. This is how you tell the source what to do when the timer fires. In our case, we merely log, but you could do whatever you like. You could also create a version of this that took a block passed into the init method and execute that when the timer fires. That would be pretty handy if you want to do specialized things for each watchdog you create. </p>

<p>Note that we cancel the timer when it fires. This is to ensure it will never fire again.</p>

<p>And finally, we start the timer running with <code>dispatch&#95;resume</code>. All sources are created in the suspended state, allowing you to set them up properly before they are started.</p>

<p>In our <code>dealloc</code>, we merely cancel the timer and release it. It does no harm if it&#8217;s already been cancelled. This covers the case where the watchdog doesn&#8217;t fire, we want to kill it and move on.</p>

<p>In <code>invalidate</code>, all we do is cancel the source. This will ensure it does not fire. It&#8217;s possible you might invalidate it just when it&#8217;s firing, but that&#8217;s OK. You were just on the cusp of the timeout, and you should have been faster!</p>

<p>If you don&#8217;t like to have to invalidate and then release the object, you could always create an invalidateAndRelease method to save some typing.</p>

<h2>Timers In General</h2>

<p>This is one specific use of a timer in GCD, clearly you can use them in many other cases where you want things to execute concurrently. If you needed to return results to your main thread, you can just use <code>dispatch&#95;async</code> to execute the code on the main queue (<code>dispatch&#95;get&#95;main&#95;queue()</code> as we&#8217;ve seen in previous posts.</p>

<p>If you just want a timer to run on the main thread, you can certainly install a GCD timer on the main queue, or you could just use NSTimer. Whatever floats your&#8230; you know.</p>

<p>If nothing else, this might give you ideas on how you could use dispatch timers in your application.</p>

<p>That&#8217;s it, enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fieryrobot.com/blog/2010/07/10/a-watchdog-timer-in-gcd/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Simple Job Queue With Grand Central Dispatch</title>
		<link>http://www.fieryrobot.com/blog/2010/06/27/a-simple-job-queue-with-grand-central-dispatch/</link>
		<comments>http://www.fieryrobot.com/blog/2010/06/27/a-simple-job-queue-with-grand-central-dispatch/#comments</comments>
		<pubDate>Sun, 27 Jun 2010 18:47:38 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[dispatch_async]]></category>
		<category><![CDATA[dispatch_sync]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[ipad]]></category>
		<category><![CDATA[libdispatch]]></category>
		<category><![CDATA[macos]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://www.fieryrobot.com/blog/?p=271</guid>
		<description><![CDATA[In my last two posts, we talked about the basics of GCD and then delved into blocks. Now we&#8217;re going to start learning how to replace your old threading code with GCD. For this post, we&#8217;ll discuss how to create a simple sequential job queue using dispatch&#95;async and friends. Starting Up&#8230; While we&#8217;ve seen that [...]]]></description>
			<content:encoded><![CDATA[<p>In my last two posts, we talked about the basics of GCD and then delved into blocks. Now we&#8217;re going to start learning how to replace your old threading code with GCD. For this post, we&#8217;ll discuss how to create a simple sequential job queue using <code>dispatch&#95;async</code> and friends.<span id="more-271"></span></p>

<h2>Starting Up&#8230;</h2>

<p>While we&#8217;ve seen that we can easily put things onto a concurrent queue, in many cases, you&#8217;ll want to create your own FIFO queue. These allow you to:</p>

<ol>
<li>guarantee order of operations</li>
<li>implement synchronization without locks</li>
<li>arrange these queues into groups to help wait on multiple queues at once</li>
<li>know when a queue is empty</li>
</ol>

<p>The synchronization case will be left for my next post, but we&#8217;ll try to cover the others here.</p>

<p>First, we need to create a queue. Simple enough:</p>

<pre><code>dispatch_queue_t myQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
</code></pre>

<p>The first parameter is just some identifier, you can use anything you want, including NULL, but reverse domain is usually a good case. You&#8217;ll actually see this name in backtraces in gdb to help you know which queue is which.</p>

<p>Once you have a queue, it&#8217;s just like we&#8217;ve seen before. We can start to put tasks on it.</p>

<pre><code>dispatch_async(myQueue, ^{
    printf("this is a block!\n");
});
</code></pre>

<p>And as noted, whenever you create your own queue, it is a FIFO queue. So everything will execute in the order you put blocks onto the queue. And you always know that the preceding block is complete before the next block executes.</p>

<h2>Finished Yet?</h2>

<p>We&#8217;ve implemented a simple job queue and can put blocks onto it, but how do you know when it is done? There are two ways you can determine this. First, you can just use <code>dispatch&#95;sync</code> to help you.</p>

<pre><code>// wait for queue to empty
dispatch_sync(queue, ^{});
</code></pre>

<p>Basically, we&#8217;re using <code>dispatch&#95;sync</code> here to force us to wait until the block passed finishes before continuing. Your thread will block until the block finally gets a chance to run and finish. At that point, you know the queue is empty (assuming you&#8217;re not doing something like posting to that queue from other queues).</p>

<p>You should generally only use the method above if you only have one queue and don&#8217;t mind blocking your thread until the task is done. For tasks that take a while, that would be bad, particularly on iOS where you&#8217;ll get watchdogged if your main thread is blocked for too long.</p>

<p>If you don&#8217;t want to wait, then you could simply push an async block to notify you when the block runs. You might, for example, do something like this during shut-down of your object (and related queue).</p>

<pre><code>- (void)shutdown {
    // don't allow more blocks to be queued
    _valid = NO;

    // allow our owner to release us while we clean up
    [self retain];

    // now push an async task to tell us when we're done
    dispatch_async(_queue, ^{
        [self allTasksDone];
    }
}

- (void)allTasksDone {
    // we're really done and ready to shut down
    // we can now release ourselves
    [self release];
}
</code></pre>

<h2>Dispatch Groups</h2>

<p>The other method to do this involves <em>dispatch groups</em>. This allows you to create and wait on multiple queues to become empty, though it would also work for one queue. 
To create a group is even simpler than creating a queue. Once you have your group, you submit blocks to the group, as such:</p>

<pre><code>dispatch_group_t group = dispatch_group_create();

dispatch_group_async(group, queue, ^{
    printf("This block is associated with our group\n");
});
</code></pre>

<p>Note that we used <code>dispatch&#95;group&#95;async</code> instead of <code>dispatch&#95;async</code>. This ensures the block is associated with the group. To wait on the group, we just call:</p>

<pre><code>dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
</code></pre>

<p>The second parameter just indicates how long to wait before giving up. Most times you&#8217;d pass <code>DISPATCH&#95;TIME&#95;FOREVER</code> as we did here.</p>

<p>Keep in mind that only blocks that you started with <code>dispatch&#95;group&#95;async</code> and therefore were associated with the group can be waited on with <code>dispatch&#95;group&#95;wait</code>. If you started that block otherwise, you&#8217;d be waiting forever, indeed.</p>

<p>Like we talked about above, this is going to block the thread you call this on though. How would we instead notify when all queues were empty? There&#8217;s an API for that:</p>

<pre><code>dispatch_group_notify(group, queue, ^{
    [self allTasksDone];
});
</code></pre>

<p>This will call <code>allTasksDone</code> when all blocks submitted to the group are finished, regardless of how many queues comprise the group.</p>

<h2>Canceling Tasks</h2>

<p>Often times, you want to put tasks onto a job queue, and then cancel one or more of them. However, you can&#8217;t cancel a block via any sort of API, so they always <em>must</em> run to completion. So it&#8217;s up to us to expedite that if need be.</p>

<p>In the example above, we wanted to wait until all tasks were done. Before submitting our sentinel block, we set <code>&#95;valid</code> to NO. We can use this to help us do cancelation and hence shut the queue time in a timely manner. Perhaps you&#8217;re writing image thumbnails and you want the current one to finish, but all others to abort. You can just check the <code>&#95;valid</code> flag in your blocks:</p>

<pre><code>dispatch_async(queue, ^{
    if (_valid) {
        [self processFile:fileURL];
    }
});
</code></pre>

<p>Once that flag is set every block that started to run would instead immediately exit.</p>

<p>Another cancelation idiom is the case where you start a task that&#8217;s searching for data on one query and the query has changed. The canonical example might be type-ahead. You can accomplish this by having a sort of ever-changing sentinel. You could do this as a integer seed, or in this case, perhaps we just store off a copy of the query we are doing and we compare that to the &#8216;current&#8217; query. We&#8217;ll need some synchronization for this because the term will be referenced from our main thread and the thread the block is running on.</p>

<pre><code>- (NSString *)currentTerm {
    @synchronized(self) {
        return [[_term copy] autorelease];
    }
}

- (void)setCurrentTerm:(NSString *)term {
    @synchronized(self) {
        if (term != _term) {
            [_term release];
            _term = [term copy];
        }
    }
}

- (void)searchWithTerm:(NSString *)term {
    self.currentTerm = term;

    dispatch_async(_queue, ^{
        [self performSearchWithTerm:term];
    });
}

- (void)performSearchWithTerm:(NSString *)term {
    if ([term isEqualToString:self.currentTerm]) {
        // do searching here and periodically double-check
        // term against self.currentTerm to see if it changed

        // When we have results, pass them to the main thread
        // Must check against current term again for safety.
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([term isEqualToString:self.currentTerm]) {
                [self searchReturnedResults:results];
            }
        }
    }
}
</code></pre>

<p>This one shows not only how to check against the current search term, but it also demonstrates another pattern where you return results.</p>

<p>Note that we store off the current term into the object, but we pass the <em>original</em> term into our block. While the block executes, we periodically compare our search term to the current term. If it changes, we stop processing and exit. However we might get as far as finding and returning results, which we then send back to the main thread. But we could have changed the current term in between the time when the block was queued for the main thread and the time that block was executed, so we check the term for one last time before returning results. It&#8217;s extremely important to do this check, otherwise you&#8217;ll end up wondering why you&#8217;re processing data that&#8217;s no longer valid, or worse.</p>

<h2>Until Next Time</h2>

<p>That pretty much covers creating and using a job queue. We discussed how to create a queue and add tasks, how to wait for tasks to complete, and also how to effectively cancel tasks in the queue. We also ended up covering how to successfully shut down an object that owns a queue. These patterns should help you replace your current use of threads with GCD. If only we could get rid of locking. Oh wait, we can! That&#8217;s for next time <img src='http://www.fieryrobot.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.fieryrobot.com/blog/2010/06/27/a-simple-job-queue-with-grand-central-dispatch/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Being a Blockhead</title>
		<link>http://www.fieryrobot.com/blog/2010/06/20/being-a-blockhead/</link>
		<comments>http://www.fieryrobot.com/blog/2010/06/20/being-a-blockhead/#comments</comments>
		<pubDate>Sun, 20 Jun 2010 18:52:26 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[iPhone]]></category>

		<guid isPermaLink="false">http://www.fieryrobot.com/blog/?p=247</guid>
		<description><![CDATA[Last time I talked about asynchronous behavior via Grand Central Dispatch. One of the core features that makes this all possible is blocks. I thought I&#8217;d take a step back this time and just talk about blocks themselves and how they can be used by your code. The Ultimate Callback If you recall, blocks are [...]]]></description>
			<content:encoded><![CDATA[<p>Last time I talked about asynchronous behavior via Grand Central Dispatch. One of the core features that makes this all possible is blocks. I thought I&#8217;d take a step back this time and just talk about blocks themselves and how they can be used by your code.<span id="more-247"></span></p>

<h2>The Ultimate Callback</h2>

<p>If you recall, blocks are snippets of code you can run which capture information about their environment as needed. That is, they behave like closures in other languages such as Javascript.</p>

<p>Because of this, they are the ultimate callback. You can pass parameters to them, and they can reference variables in the current scope the block is introduced in. You can also pass blocks around as objects, and copy them as needed, as we&#8217;ll see later.</p>

<p>We&#8217;ve already seen the most basic callback in use in the last post, where we had a simple block that looked like this:</p>

<pre><code>^{ printf("this is a block"); }
</code></pre>

<p>This is what you&#8217;d use for a call to dispatch_async, etc. This is essentially a block that takes no parameters and returns no result. You can actually typedef such a thing as follows:</p>

<pre><code>typedef void (^GenericCallback)(void);
</code></pre>

<p>Or just define the types directly as:</p>

<pre><code>void (^)(void) myCallback;
</code></pre>

<p>It&#8217;s pretty much the exact same syntax as a function pointer, but you substitute a ^ for the *. But blocks can also take parameters and return values:</p>

<pre><code>NSString *(^)(int a, NSString *b);
</code></pre>

<p>In fact, some of the newer APIs take blocks now instead of using callbacks or target/selector. Consider this method in NSArray.h:</p>

<pre><code>- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx,
                 BOOL *stop))block;
</code></pre>

<p>This method allows you to iterate over all items in the array. Each time your block is called, you get the object, the index, and a stop parameter (if you want to terminate iteration). You can use it as such:</p>

<pre><code>[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSLog(@"Item %d is %@", idx, obj);
}];
</code></pre>

<p>So in its most basic use, it becomes an inline callback. But unlike a normal callback, it has the advantage of context. Let&#8217;s say we have an object&#8217;s identifier. I need to compare that to each item in an array&#8217;s identifier until we find a match. You can do the following:</p>

<pre><code>NSUInteger index;
NSString *myIdentifier = myObject.identifier;

index = [myArray indexOfObjectPassingTest:
                 ^(id obj, NSUInteger idx, BOOL *stop) {
                    return ([obj.identifier isEqualToString:myIdentifier]);
                 }];
</code></pre>

<p>The advantage here obviously is that we don&#8217;t need to pass any sort of &#8216;userData&#8217; or &#8216;refCon&#8217; along with the block. That comes for free because myIdentifier is in scope as far as the block is concerned. Clearly this is far more powerful than ye callbacks of olde.</p>

<p>As the implementer of such a function, you call blocks just like you call a function. In this example, we&#8217;ll define a contrived method that takes a math function that operates on its members.</p>

<pre><code>- (int)performMathFunction:(int (^)(int a, int b))operation {
    return operation(_a, _b);
}

// then someplace later...
int result1 = [self performMathFunction:^(int a, int b) { return a + b; }];   
int result2 = [self performMathFunction:^(int a, int b) { return a / b; }];
</code></pre>

<p>Kind of useless in and of itself, but the point is clear in that you can use a block where you might have otherwise used a callback, but now you have the advantage of allowing the callback to take its data with it.</p>

<h2>Blocks as Objects</h2>

<p>Another benefit is that you can hold onto blocks as you would objects. There are two methods defined for copying and releasing blocks: <code>Block&#95;copy</code> and <code>Block&#95;release</code>. These are handy if you want to allow a block to be kept around by an implementation to be called later. This is ultimately what dispatch_async uses to take your block and run it over on some other thread. You only generally need to use it if you will be running the block after the function that passed the block will have been exited by the time it is called.</p>

<p>Please note that if you are using a synchronous function such as the NSArray methods above, you don&#8217;t need to do any copy/release because it&#8217;s all happening right then and there in your thread. This is only for those cases where you want to for whatever reason call a block sometime later.</p>

<p>When using Objective-C, you can treat them like almost any other object and just use <code>copy</code> and <code>release</code>. For example, another contrived example:</p>

<pre><code>@class MyObject;

typedef void (^MyCompletionHandler)(MyObject* object);

@interface MyObject : NSObject {
    ...
    MyCompletionHandler        _completion;
}

@property(nonatomic, copy) MyCompletionHandler   completionHandler;

@end

@implementation MyObject

...

// Implementing this just to show it in action, 
// but you could just use @synthesize
- (void)setCompletionHandler:(MyCompletionHandler)completion {
    [_completion release];
    _completion = [completion copy];
}

...

- (void)taskIsComplete {
    _completion(self);
}
@end
</code></pre>

<p>When you copy a block, it&#8217;s context goes with it. If you copy a block in Objective-C, the objects referenced therein will get retained when the block is copied. We touched on this last time. Remember though that in C (or really, when using C types like CFArrayRef), this does <em>not</em> happen, and you will need to retain objects before your block and release them inside to ensure that when the block is run it really has a reference to the object.</p>

<h2>Be Cautious of Loops</h2>

<p>This copying/retaining semantics of blocks is very useful as it means your objects won&#8217;t go away while your block is being executed on some other thread, but you can also get into trouble if you happen to be using them only on one thread and the context in a block contains a reference to some parent structure. You&#8217;ll get into a retain-loop. Consider a UITableViewCell subclass that you want to initialize with a block to perform some action:</p>

<pre><code>// inside your controller's tableView:cellForRowAtIndexPath:
cell = [[MyCell alloc] initWithBlock:^(MyCell* cell) {
           [self adjustCell:cell];
       }];
</code></pre>

<p>So here we have a block that calls a method on the controller. Simple enough. But when that cell is created, it&#8217;s init method might copy the block to ensure the block is valid at all times. The problem is, it references <code>self</code>. But that <code>self</code> is the view controller. So you have a view controller retained by one of its descendants. This creates a retained object loop that ultimately means this controller will never get released.</p>

<p>The only way I&#8217;ve found to deal with this is by creative use of <code>__block</code> variables. But we haven&#8217;t talked about that, now have we? Guess it&#8217;s time&#8230;</p>

<h2>Modifying Local Variables in a Block</h2>

<p>While blocks can reference variables in the context they are defined, those variables are read-only. This is done (I presume) for efficiency&#8217;s sake, and 99 times out of 100 this is fine. However, there are times when you want to change the value of one of those variables. The way you do this is to prefix them with the <code>__block</code> modifier. Consider:</p>

<pre><code>int     x = 10;

dispatch_sync(aQueue, ^{
    x = x + 10;
    printf("block says x is %d\n", x);
});

printf("x is %d\n", x);
</code></pre>

<p>Yet another contrived example, but here we want to call a block via <code>dispatch&#95;sync</code>. Unlike <code>dispatch&#95;async</code>, <code>dispatch&#95;sync</code> executes code synchronously. You might wonder why you&#8217;d do that. Well, you&#8217;ll have to wait until another blog post <img src='http://www.fieryrobot.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  In any case, this block wants to modify the value of <code>x</code>. The output of this is:</p>

<pre><code>block says x is 20
x is 10
</code></pre>

<p>Not quite what you expected, perhaps. The variable <code>x</code> was perfectly mutable inside the block, but it never affected the original scope. We can fix this easily just by adding <code>__block</code>:</p>

<pre><code>__block int x = 10;
</code></pre>

<p>And then our output is what you&#8217;d expect:</p>

<pre><code>block says x is 20
x is 20
</code></pre>

<p>And all&#8217;s right with the world again.</p>

<p>But how does this knowledge help us avoid the retain cycle we saw above? Well, it turns out that <code>&#95;&#95;block</code> variables are actually <em>not</em> retained when the lock is copied. So you can do this:</p>

<pre><code>// inside your controller's tableView:cellForRowAtIndexPath:
__block me = self;
cell = [[MyCell alloc] initWithBlock:^(MyCell* cell) {
           [me adjustCell:cell];
       }];
</code></pre>

<p>Since the self doesn&#8217;t get retained this time, we avoid the retain cycle. While it strikes me as iffy, it does work, and it&#8217;s the only way I&#8217;ve found to deal with this situation. You can&#8217;t simply avoid copying the block if you want to call it later, because the scope will be gone by the time the function that declared the block exits. That will lead to nothing but sadness.</p>

<h2>Now You&#8217;re a Blockhead, Too</h2>

<p>At this point, you know just about everything there is to know about blocks. Some of what we&#8217;ve talked about here is going to help us when we discuss using blocks and dispatch queues to implement synchronization in a future post. Believe me, GCD does it all. It&#8217;s one technology that might convince you to make your apps depend on it completely to the point of requiring it to run. Doing the types of things GCD can do any other way seems so&#8230; primitive.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fieryrobot.com/blog/2010/06/20/being-a-blockhead/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Threading is Dead. Long Live Threading!</title>
		<link>http://www.fieryrobot.com/blog/2010/06/12/threading-is-dead-long-live-threading/</link>
		<comments>http://www.fieryrobot.com/blog/2010/06/12/threading-is-dead-long-live-threading/#comments</comments>
		<pubDate>Sat, 12 Jun 2010 16:49:40 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[dispatch_async]]></category>
		<category><![CDATA[gcd]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[ipad]]></category>
		<category><![CDATA[libdispatch]]></category>
		<category><![CDATA[macos]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://www.fieryrobot.com/blog/?p=197</guid>
		<description><![CDATA[I stated in a past post that threads are evil. I still stand by that statement. Adding threads to an application has historically been fraught with issues. Many stem from people not quite understanding all of the situations can arise, etc. Oh sure, you might know what a deadlock is, but do you know all [...]]]></description>
			<content:encoded><![CDATA[<p>I stated in a past post that threads are evil. I still stand by that statement. Adding threads to an application has historically been fraught with issues. Many stem from people not quite understanding all of the situations can arise, etc. Oh sure, you might know what a deadlock is, but do you know all the circumstances they can occur? How does one safely shut a thread down? Did the owning object go away? It&#8217;s not as simple as it seems in most cases.</p>

<p>But what if I could thread until the break of dawn and not have to worry as much about those situations? That&#8217;s exactly what Grand Central Dispatch gives you on Mac OS X, and now iOS — access to concurrency without nearly as much pain.<span id="more-197"></span></p>

<p>This new world, however, does require you to think about problems a bit differently. I, at least, am so used to threading the old fashioned way that I had to figure out how to use dispatch_async and friends instead of my old cohorts.</p>

<p>One thing I will throw out there first is that threading with Obj-C/Foundation is so much easier than doing all the nasty work yourself. Methods like detachThreadSelector, et. al. go a long way towards making life simpler. NSOperation is also a big help. But GCD takes us beyond that with blocks (closures) and a full set of lower-level primitives that interact with Obj-C in ways that make sense and do most of the heavy lifting. But there are certainly some things you need to keep in mind, particular if you are using Obj-C.</p>

<h2>Blocks</h2>

<p>The first thing to learn about in this new world (and really, the thing that makes this all possible) is blocks. Blocks are essentially what other languages refer to as closures. All that ultimately matters is that it&#8217;s a way of designating a snippet of code to run. Think of them as fancy callbacks which can take any data they need with them (i.e. their context is omnipresent).</p>

<p>You specify a block with a special syntax. Ultimately, you enclose a block with ^{}:</p>

<pre><code>^{ printf("this is a block!\n"); }
</code></pre>

<p>In the interest of keeping things simple, we&#8217;ll stop there and get onto some other basics.</p>

<h2>Dispatch Queues</h2>

<p>Typically, you&#8217;ll put blocks onto <em>dispatch queues</em>. There are two types of queues, concurrent, and FIFO. Regardless of the type of queue, you always know that blocks will be started in the order they are placed onto a particular dispatch queue. But in the concurrent case, they will be run on separate threads, whereas in the FIFO case you can run blocks one after the other, each one waiting for the previous one to finish first.</p>

<p>You can access a queue in three ways:</p>

<ol>
<li>call <code>dispatch&#95;get&#95;global&#95;queue()</code>. This will give you a built-in concurrent queue. There are three, each at a different priority (low, medium, high).</li>
<li>call <code>dispatch&#95;get&#95;main&#95;queue()</code>. This queue represents a dispatch queue on the main thread. This is a FIFO queue, and tasks are run at &#8216;event time&#8217; (i.e. inside the run loop).</li>
<li>create your own queue with <code>dispatch&#95;queue&#95;create()</code>. This will always give you your very own FIFO queue.</li>
</ol>

<p>Concurrent queues will create as many threads as needed to run the tasks. This doesn&#8217;t mean it will run as many threads as there are tasks, however, it is up to GCD to figure out how many threads make sense for the number of tasks which are attempting to run. So you might not always get 100% concurrency, as it might limit the number of threads to something smaller than the number of blocks waiting to run. But ultimately, to you the coder, it doesn&#8217;t matter. You just know that your tasks will be run at some point.</p>

<p>One thing to pay attention to is that concurrent queues are really concurrent. Just because they have the word &#8216;queue&#8217; in their name doesn&#8217;t mean tasks run one after the other. It means they will <em>start</em> in a predictable order, but they will most often times be running at the same time. So only put tasks on concurrent queues that you can safely run in parallel. Many people seem to get bitten by this.</p>

<h2>Queues vs. Threads</h2>

<p>One of the things that confused me at first was that queues have nothing to do with threads you create. The only thread with a queue reserved for it is the main thread. I was so used to a life where each thread you create would get its own runloop and event queue (at least in Carbon) that I was thinking it might be the same here. But it is not (nor should it be). There is a function called <code>dispatch&#95;get&#95;current&#95;queue()</code> (so really, there&#8217;s a fourth way to access a dispatch queue), but it is really for use inside a block that&#8217;s being executed. Calling it outside of a block will yield the default concurrent queue, which is generally not very meaningful.</p>

<p>What this means is that if you create a thread, that thread has nothing to do with GCD, and doesn&#8217;t tie into GCD at all. Of course, with GCD in the mix, if you create a thread, you might be doing something you don&#8217;t have to do. You can pretty much accomplish every thing you used to via threads with dispatch queues and blocks (and some other constructs we won&#8217;t discuss right now). Heck, you can even implement synchronization without locks. But that&#8217;s for another time.</p>

<h2>Running Tasks</h2>

<p>We&#8217;ve now talked about the two parts we need in order to finally run a task concurrently. In order to start an asynchronous task, you use <code>dispatch&#95;async()</code>. Let&#8217;s say we wanted to run that block we used above. Here&#8217;s what we&#8217;d do:</p>

<pre><code>dispatch_queue_t queue = dispatch_get_global_queue(
                                 DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{
    printf("this is a block!\n");
});
</code></pre>

<p>That&#8217;s all there is to it. First we got access to one of the global concurrent queues, running a normal priority, then we called dispatch_async, specifying the queue and the block to run. It&#8217;s common to use the formatting you see above as it make reading the code a bit clearer.</p>

<p>I mentioned that blocks behave like closures and are run with their context intact. Let&#8217;s see that in action:</p>

<pre><code>int i = 20;

dispatch_async(queue, ^{
    printf("The number was %d\n", i);
});
</code></pre>

<p>This will print:</p>

<pre><code>The number was 20
</code></pre>

<p>So all variables in scope at the time the block was created are valid for the block&#8217;s execution later. In this case, we&#8217;re able to access <code>i</code> without issue.</p>

<p>So great, we ran a task. Yay for us, what if we need to know when it&#8217;s done? There are a couple of solutions, but let&#8217;s stick with the purity of what we&#8217;re working with: <code>dispatch&#95;async</code> to the rescue!</p>

<pre><code>dispatch_async(queue, ^{
    NSArray *results = ComputeBigKnarlyThingThatWouldBlockForAWhile();

    // tell the main thread
    dispatch_async(dispatch_get_main_queue(), ^{
        ProcessResults(results);
    });
});
</code></pre>

<p>In this case, after doing whatever long task you wished to make concurrent, we can then just use <code>dispatch&#95;async</code> again to execute the <code>ProcessResults</code> function on the main thread. This is really the same thing as doing <code>performSelectorOnMainThread:</code>, but more flexible in that you aren&#8217;t restricted to what you can &#8216;pass&#8217; to it.</p>

<h2>Blocks in Objective-C</h2>

<p>When used in Objective-C, block automatically retain any objects referenced within them. This is extremely helpful, as often times you might reference <code>self</code>, let&#8217;s say. This means your object won&#8217;t go away until that block has executed. So you&#8217;ll never run into situations where objects used inside the block have disappeared out from under you.</p>

<p>This isn&#8217;t true in C. If you were using CoreFoundation types in a C function, you&#8217;ll need to retain objects before calling dispatch_async and release them inside the block. For example:</p>

<pre><code>void SaveArrayAsync(CFArrayRef array) {
    CFRetain(array);

    dispatch_queue_t queue = dispatch_get_global_queue(
                                 DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_async(queue, ^{
        SaveToDisk(array);
        CFRelease(array);
    }
}
</code></pre>

<p>But, as mentioned, in Objective-C, it&#8217;s not even something you need to think about.</p>

<pre><code>- (void)saveArrayInBackground:(NSArray *)array {
    dispatch_queue_t queue = dispatch_get_global_queue(
                                 DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_async(queue, ^{
        [self saveToDisk:array];
    }
}
</code></pre>

<h2>More to Come</h2>

<p>We&#8217;ve covered just enough to start to be dangerous, but I think we&#8217;re at a good stopping point for now. I&#8217;ll be writing several more entries on using GCD and specifically how to take an old threaded concept and what you&#8217;d instead do with GCD. I&#8217;ll try to be regular about timing of these articles, so keep your eyes peeled.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fieryrobot.com/blog/2010/06/12/threading-is-dead-long-live-threading/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>If Only I Could Write Like This</title>
		<link>http://www.fieryrobot.com/blog/2010/05/29/if-only-i-could-write-like-this/</link>
		<comments>http://www.fieryrobot.com/blog/2010/05/29/if-only-i-could-write-like-this/#comments</comments>
		<pubDate>Sat, 29 May 2010 20:55:14 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.fieryrobot.com/blog/?p=191</guid>
		<description><![CDATA[I ran across this quote from Oliver Reichenstein, and it embodies my thinking completely, though I&#8217;ve never been able to put it into such words. We should use original tools to create iPad apps, not because Steve Jobs said so, but because these tools create products with flesh and bone, that is: an understanding of [...]]]></description>
			<content:encoded><![CDATA[<p>I ran across this quote from <a href="http://informationarchitects.jp/wired-on-ipad-just-like-a-paper-tiger/">Oliver Reichenstein</a>, and it embodies my thinking completely, though I&#8217;ve never been able to put it into such words.</p>

<blockquote>We should use original tools to create iPad apps, not because Steve Jobs said so, but because these tools create products with flesh and bone, that is: an understanding of both the purpose, the potential and the limits of the iPad technology.</blockquote>

<p>I&#8217;ve never been a fan of cross-platform frameworks, even though I&#8217;ve been involved in four to speak of to date (not always by choice). I like to think I&#8217;m pretty good at it at this point, but even the best of us ends up with mediocre platform support or performance because you&#8217;re trying to wedge your idea of the universe onto another. And we know from watching Fringe what happens when two universes meet.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fieryrobot.com/blog/2010/05/29/if-only-i-could-write-like-this/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I Love Xcode</title>
		<link>http://www.fieryrobot.com/blog/2009/10/04/i-love-xcode/</link>
		<comments>http://www.fieryrobot.com/blog/2009/10/04/i-love-xcode/#comments</comments>
		<pubDate>Sun, 04 Oct 2009 20:31:31 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.fieryrobot.com/blog/?p=160</guid>
		<description><![CDATA[A while back I wrote a post called &#8220;I hate Xcode&#8221;. These days I feel I need to post a revised statement based on my more recent experience with Xcode which can be summed up with: I Love Xcode. I guess this is much akin to Leonard Nimoy writing &#8220;I am not Spock&#8221; and later [...]]]></description>
			<content:encoded><![CDATA[<p>A while back I wrote a post called &#8220;I hate Xcode&#8221;. These days I feel I need to post a revised statement based on my more recent experience with Xcode which can be summed up with: I Love Xcode. I guess this is much akin to Leonard Nimoy writing &#8220;I am not Spock&#8221; and later writing &#8220;I am Spock&#8221;.
<span id="more-160"></span>
When I wrote the original post, I really did want to throw Xcode off of a bridge. And Visual Studio did seem better to me. It was more stable and faster. But in the last few releases, Xcode has really stepped up its game, particularly in 3.2, and meanwhile, VS has gotten worse and slower. Thank Osiris that I never have to use VS again. </p>

<p>I think the true turning point started at around Xcode 3.0. Xcode is now quite simply the best IDE I&#8217;ve ever used. Most all of my complaints have been solved over time, and admittedly I&#8217;ve figured out a few things along the way that made me finally get how it all works. I thought I&#8217;d point out a few of the things that made me realize that Xcode rocks. If you&#8217;re an Xcode aficionado, I&#8217;m sure you&#8217;ll already know these.</p>

<h2>Fast Compilations</h2>

<p>It&#8217;s just simply super fast to compile. On my last project, I was able to clean in about 5 minutes on an iMac. In Visual Studio on my quad-core PC it took like 20 minutes clean or not. Granted it has more files to build, but wow. Slow. To the point that any time you realized you&#8217;d have to build Windows and you weren&#8217;t at top-of-tree you were like &#8220;there goes a half hour&#8221;. These days, doing iPhone apps, my app at work takes about 20 seconds to clean build. And more like about 2 second to build/link and fire up the simulator for a quick change.</p>

<h2>Settings That Are Useful</h2>

<p>Setting project settings used to frustrate me on Xcode. You have project settings, and then you have target settings, and it just seemed like too much. I&#8217;ve finally gotten to get the how and the why around this and I understand it all now. Recently though I had to mess with settings, and I think if it weren&#8217;t for two features, I&#8217;d still be trying to find and set the settings correctly:</p>

<ul>
<li>ability to filter settings. Type &#8216;install&#8217; in the search box and get all settings having to do with install paths, etc. Avoids having to scan a big giant list of options.</li>
<li>the fact that Xcode actually shows you the computed paths. If you click something it might be generated from variables, etc. but once it&#8217;s commited you see the path it&#8217;s going to use. I can&#8217;t begin to tell me how much time that saved me the other day when I was wondering why something wasn&#8217;t working. This was always a source of frustration in Visual Studio for me.</li>
</ul>

<p>They might not seem like OMG features on the surface, but the time it saved makes me say OMG anyway.</p>

<h2>Code Completion</h2>

<p>The code completion feature of Xcode used to be frustrating to use, but in recent releases it works extremely well. It&#8217;s smart completion combined with text macros completing code fragments like if statements, etc. makes it damn quick to write code. And furthermore, you can adjust the templates of the generated code to match your code style either by creating your own text macros or by setting some defaults on the command line by setting the XCCodeSenseFormattingOptions property. For example, I like open braces of a block to always be on the next line. It help readability for me and it also helps editing a bit. Just setting a few options using that default and you can get the Xcode text completion to do your bidding.</p>

<h2>Syntax-Aware Editing</h2>

<p>I love the syntax-aware editing, particularly with cut and paste. Often times I&#8217;ll even cut and paste a section of code just to make it fix it up (maybe there&#8217;s another way but I&#8217;m too lazy to find out). As mentioned above, you can tweak some defaults if the code style doesn&#8217;t please you. But it&#8217;s nice to type a &#8216;}&#8217; and have it put it where it belongs. Or split a call to an objective-c method across multiple lines and have it line everything up for you at the colons. One other thing that I like is when you perhaps take a method and add another call to it. For example, let&#8217;s say you typed: <code>[foo retain]</code> and now you want to add <code>autorelease</code>. Just follow it up with <code>autorelease]</code> and Xcode will put the starting [ in the right place. It doesn&#8217;t always get it right, but in most cases it does. Very nice, as it is certainly a bit annoying to otherwise have to go back to the start yourself just to add a starting [, which has always been one of my nits about obj-c syntax. I like it when the tools make my nits a non-issue.</p>

<h2>Refactoring Tools</h2>

<p>The refactoring tools that Xcode provides are really nice. The current transformations that are supported are definitely helpful at times, and I hope they continue to think of more goodness they can add here.</p>

<h2>Slipstream Drive</h2>

<p>With all the above features — in general lots of &#8216;little things&#8217; that make things just work — Xcode allows me to write code incredibly fast. I feel like code just flows out of my fingers and the IDE just knows what to do with it. Occasionally though, I&#8217;ll long for a couple of smaller niceties from Visual Studio, or perhaps the code completion isn&#8217;t quite doing what I want, and it kind of knocks me out of slipstream drive. I&#8217;ve recently filed a couple of enhancement requests for them. We&#8217;ll see what comes of them, but if they did manage to get them in, I would truly have an all-powerful programming tool at my fingertips.</p>

<p>I&#8217;m sure there&#8217;s more things (data modeling, etc.) but I haven&#8217;t used all those features. My bliss these days comes from just being able to sit down and get incredible amounts of work done in a relatively small amount of time. To me, that&#8217;s what makes Xcode so amazing and pleasurable to use. </p>

<p>Bet you didn&#8217;t expect to hear me ever say that, now did you? <img src='http://www.fieryrobot.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.fieryrobot.com/blog/2009/10/04/i-love-xcode/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>My Journey To Tweetsville</title>
		<link>http://www.fieryrobot.com/blog/2008/11/15/my-journey-to-tweetsville/</link>
		<comments>http://www.fieryrobot.com/blog/2008/11/15/my-journey-to-tweetsville/#comments</comments>
		<pubDate>Sat, 15 Nov 2008 20:31:11 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[iPhone]]></category>

		<guid isPermaLink="false">http://www.fieryrobot.com/blog/?p=147</guid>
		<description><![CDATA[Now that Tweetsville is out there, I thought I&#8217;d reflect a bit about where it came from and how it came to be. When the app store opened, I downloaded several Twitter clients. Each was interesting in their own right, but I couldn&#8217;t use any of them because of one reason: the scrolling performance. I [...]]]></description>
			<content:encoded><![CDATA[<p>Now that <a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=294887301&amp;mt=8">Tweetsville</a> is out there, I thought I&#8217;d reflect a bit about where it came from and how it came to be.</p>

<p>When the app store opened, I downloaded several Twitter clients. Each was interesting in their own right, but I couldn&#8217;t use any of them because of one reason: the scrolling performance. I didn&#8217;t get why everyone&#8217;s scrolling was not as smooth as any of the built-in iPhone applications. For me, it made the apps frustrating to use, to the point that I just never used them.</p>

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

<h2>A Simple Proof</h2>

<p>As an experiment, I wanted to prove that I could make something that scrolled as good as the Apple-made stuff. I had already done other samples using the Twitter API as part of Blueprint at Yahoo! as well as in a Widget for Konfabulator I worked on but never finished. So I figured it would be fairly quick to throw something together.</p>

<p>I wrote a simple web fetcher and then did a rudimentary list. Originally, it was completely a navigation based app. You&#8217;d get a list of items such as &#8216;With Friends&#8217;, &#8216;History&#8217;, etc. and click those and get the listing of 20 tweets (the default that you get with the API). It was at this point that I started messing with getting the scrolling fast. In the end, it was smooth as silk. But I also didn&#8217;t have features such as the current balloon look and clickable links and @names.</p>

<p>The clickable links took me quite a while to get to work. I spent much time working on line breaking and making sure it was as efficient as it could be, using Instruments to find and eliminate bottlenecks.</p>

<p>After that, I had something that could line break beautifully and yet it still scrolled incredibly fast. Implementing the balloon look however, did slow it down a bit, but again I spent a lot of time trying to cache and get things to the point that you see it today.</p>

<p>But even after all that, there was still tons to do. I mean, it was really just something to prove to myself I could do this. But at this point, I realized I was onto something real here and could really build something exciting. But there were plenty of competition out there. Why build another Twitter app? I wasn&#8217;t really sure, but I kept going anyway to see where it took me. By the time I got to the end, I knew I had something big on my hands.</p>

<h2>Making It Real</h2>

<p>For the next few weeks I worked pretty much 24/7 getting things to cache properly, push things off onto threads as much as possible, use a real database, etc. and make sure that things just worked correctly. Despite the simplicity of what Twitter is, making an application to really behave properly and ensure that things are always as you expect is pretty darn hard. Even something as &#8216;simple&#8217; as clicking a tweet and then iterating your tweets with the up and down arrows in the upper right was interesting. Not because of the iteration of the items, but because you now have yet another view that needs to be aware of state changes in the application. For example, if you favorite something, I needed to make sure that if it was showing elsewhere in the UI the change was reflected. Good times.</p>

<p>I also rewrote certain sections more than once to get things right. The database for example, was originally just a plist, but the more complicated the UI became, the more necessary SQLite was. And that had to be threaded for even more fun. I had also originally started with MGTwitterEngine, but ended up writing my own engine for two reasons: </p>

<ol>
<li>design-wise, MGTwitterEngine didn&#8217;t fit with what I needed to to (it was too centralized, I needed many delegates, not just one). </li>
<li>I decided to use JSON instead of XML to try to keep the data smaller and simpler to parse. XML really is a pain to deal with.</li>
</ol>

<p>And since I didn&#8217;t find a JSON parser that seemed to be small enough and simple enough to integrate, I wrote one. Admittedly, it&#8217;s been something I&#8217;ve wanted to do for a while. I&#8217;m sure somewhere out there there&#8217;s a JSON parser that would have fit the bill, but I didn&#8217;t find it in my cursory search of the interweb tubes.</p>

<h2>Details, Details</h2>

<p>You know all those &#8216;standard&#8217; form controls you see in all the Apple applications? Yeah, they ain&#8217;t standard. So a bit of time was put into creating my own version of those constructs and making them look and behave as closely to the Apple stuff as I could.</p>

<p>I also needed to handle image uploads and tweet compositions, loading followers so you can help address messages, doing the first run screen, etc. Lots of little things to make stuff right.</p>

<p>And even after I thought I had everything done, I ended up rewriting the messaging section to what you see today. It originally had inbox and sent like the web site, but one of my beta testers suggested a threaded view. At first I was like &#8220;man, that&#8217;s going to take forever&#8221;, but it only took me a day or two to get right. Most of my time in fact was spent drawing the stupid balloons to try and match the SMS app, only this time in delicious purple!</p>

<p>That was the making of 1.0. Right before I handed it over to Tapulous, I also added:</p>

<ul>
<li>Flickr upload support</li>
<li>Re-tweet functionality</li>
<li>Ability to quit during writing a tweet and come back to where you left off the next time you launch.</li>
</ul>

<p>I know there are several other thing that people want. I originally did envision adding things like multiple account support, etc. and I see that people also really want to have it save where you last were and not jump to the top when you load tweets. That one actually came up during development and there seemed to be strong arguments on both sides. So I left it as it was, but perhaps Tapulous can add that as an option.</p>

<p>People also have been asking for the ability to tap the status bar and have it jump to the top, but it already does that (the iPhone frameworks do it for you in fact). Perhaps there&#8217;s a bug in there that stops it from working sometimes.</p>

<p>So that&#8217;s my story, and I&#8217;m sticking to it. The best part for me has been seeing people&#8217;s comments on Twitter which echo exactly those attributes I held dear in its inception:</p>

<ul>
<li>UI speed. It tries its best to not get &#8216;stuck&#8217;. It only now gets stuck when it&#8217;s loading the table for the first time. I hope.</li>
<li>Simplicity. It&#8217;s not glossy black. It&#8217;s just iPhone.</li>
<li>Power. You can do almost everything the Twitter API allows: follow friends, drill down in a user&#8217;s history or followers, search for your favorite terms, etc.</li>
</ul>

<h2>Thanks</h2>

<p>I want to thank everyone that helped me test the application and suggested features, etc. This includes Arlo Rose, Rob Marquardt, Karl Adam and Aaron Hurley. These people had much input into the end design. Arlo suggested the use of the Tab Bar over the nav-style interface. Karl caused me to go to threaded messages, Rob and Aaron both suggested many different enhancements to make things more user-friendly and do what you&#8217;d expect. You can blame Rob in particular for my adding Flickr upload. </p>

<p>Again, thank you all. It was a great project!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fieryrobot.com/blog/2008/11/15/my-journey-to-tweetsville/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Tweetsville Update</title>
		<link>http://www.fieryrobot.com/blog/2008/11/04/tweetsville-update/</link>
		<comments>http://www.fieryrobot.com/blog/2008/11/04/tweetsville-update/#comments</comments>
		<pubDate>Tue, 04 Nov 2008 22:51:54 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[iPhone]]></category>

		<guid isPermaLink="false">http://www.fieryrobot.com/blog/?p=139</guid>
		<description><![CDATA[Just wanted to post an update as to what was happening with Tweetsville, my iPhone Twitter app. First, it&#8217;s been approved for sale! But I haven&#8217;t seen it show up and sadly I don&#8217;t have a link to it. Read on for why. The main reason the app was delayed so long coming out is [...]]]></description>
			<content:encoded><![CDATA[<p>Just wanted to post an update as to what was happening with Tweetsville, my iPhone Twitter app.</p>

<p>First, it&#8217;s been approved for sale! But I haven&#8217;t seen it show up and sadly I don&#8217;t have a link to it. Read on for why.</p>

<p>The main reason the app was delayed so long coming out is because I had been been trying to figure out exactly what to do with it. I might be in a situation soon that will actually prevent me from being able to maintain the application, so I wanted to see if I could find a good stewart for my baby. I&#8217;ve chosen to hand the application over to <a href="http://www.tapulous.com">Tapulous</a>, maker of Tap Tap Revenge, Twinkle, FriendBook, Fortune and Collage, with whom I have a good working relation.</p>

<p>I think this is going to be great for Tweetsville, as they have better resources at their disposal to help support and grow the application. I also think they have some technology which can help Tweetsville be even better than it is. At the same time, there&#8217;s some stuff I did for my app that I believe will benefit Tapulous.</p>

<p>There is no plan to have Twinkle and Tweetsville merge. They are to be separate applications with separate audiences. Twinkle is about locality and the Tapulous network, and Tweetsville is purely a Twitter application.</p>

<p>One of the advantages here for users is that there will be choice. There will ultimately be two versions of Tweetsville. The first will be a paid version currently slated for $3.99. The second will come a few weeks later and will be a free ad-supported version.</p>

<p>I&#8217;m confident this will move is the best thing for the Tweetsville app as well as users in the long run. You&#8217;ll get more choices and better support than I would have been able to provide on my own. I feel the app is in good hands, as I have a great working relationship with Tapulous (I&#8217;m actually doing a little work on Twinkle 1.3 these days too).</p>

<p>So look for it to appear in the App Store on Monday the 10th of November!</p>

<p><strong>Update</strong> Actually the date is apparently going to be the 12th.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fieryrobot.com/blog/2008/11/04/tweetsville-update/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>The Simple Beauty of clearColor</title>
		<link>http://www.fieryrobot.com/blog/2008/10/22/the-simple-beauty-of-clearcolor/</link>
		<comments>http://www.fieryrobot.com/blog/2008/10/22/the-simple-beauty-of-clearcolor/#comments</comments>
		<pubDate>Thu, 23 Oct 2008 00:21:07 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[iPhone]]></category>

		<guid isPermaLink="false">http://www.fieryrobot.com/blog/?p=137</guid>
		<description><![CDATA[I&#8217;ve recently discovered the simple beauty of [UIColor clearColor] used for a background color. Previously I had been doing stuff like: self.opaque = NO; self.backgroundColor = nil; self.clearsContextBeforeDrawing = YES; But all I really needed to do was: self.backgroundColor = [UIColor clearColor]; Same transparency, and I&#8217;m guessing (hoping?) that it might be a bit more [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently discovered the simple beauty of <code>[UIColor clearColor]</code> used for a background color. Previously I had been doing stuff like:</p>

<pre><code>self.opaque = NO;
self.backgroundColor = nil;
self.clearsContextBeforeDrawing = YES;
</code></pre>

<p>But all I really needed to do was:</p>

<pre><code>self.backgroundColor = [UIColor clearColor];
</code></pre>

<p>Same transparency, and I&#8217;m guessing (hoping?) that it might be a bit more efficient (unless of course, the innards look for clear color and effectively do what I used to).</p>

<p>Hey, even if it&#8217;s not more efficient, it&#8217;s certainly simpler to type and it seems to have the same effect!</p>

<p>Sadly, this is one thing I didn&#8217;t figure out on my own, but rather spied in some other sources, but I wanted to throw it out there for &#8216;all uh yous&#8217;.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fieryrobot.com/blog/2008/10/22/the-simple-beauty-of-clearcolor/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Recursive Locks Will Kill You!</title>
		<link>http://www.fieryrobot.com/blog/2008/10/14/recursive-locks-will-kill-you/</link>
		<comments>http://www.fieryrobot.com/blog/2008/10/14/recursive-locks-will-kill-you/#comments</comments>
		<pubDate>Wed, 15 Oct 2008 00:11:18 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.fieryrobot.com/blog/?p=133</guid>
		<description><![CDATA[A while back, at Adobe, I ran into a most evil bug that took me hours to track down. In the end, it was the end results of people violating what (to me) are the three tenets of threaded programming. This post is what I ended up establishing as the thread safety guidelines for our [...]]]></description>
			<content:encoded><![CDATA[<p>A while back, at Adobe, I ran into a most evil bug that took me <strong>hours</strong> to track down. In the end, it was the end results of people violating what (to me) are the three tenets of threaded programming. This post is what I ended up establishing as the thread safety guidelines for our project.</p>

<p>Before digging into it, I should say this: threads are evil. If you don&#8217;t believe this, then I believe you are made of living tissue over metal endoskeleton. You should endeavor to avoid threads at all cost. In most cases, timers are your best friend. Know them. Love them.</p>

<p>Of course, there are times when you need to use threads. I needed to add a few threaded operations to my iPhone application to make sure the UI stayed responsive. On the project at Adobe, we were doing thumbnailing of images, definitely something you don&#8217;t want happening on the main thread.</p>

<h2><span id="more-133"></span>1. Avoid recursive locks</h2>

<p>A recursive lock is a lock which allows the same thread that locked it to lock it again. The advantage is that you don&#8217;t need to worry about what&#8217;s locked and what&#8217;s not on any particular thread. They also make it easy to retrofit locks into existing code.</p>

<p>The problem though is they most often end up being used to lock large pieces of code for indeterminate amounts of time. This makes things very coarse-grained. They also lead to issues where if you didn&#8217;t unlock the exact right amount of times, you will leave a thread holding the lock forever. It&#8217;s very easy for this to happen. And these problems are nearly impossible to find because the lock that was taken is usually very far away from where the hang/deadlock happens later. </p>

<p>Better to use a real honest-to-goodness lock. This means that if a thread tries to lock a lock that&#8217;s already, well, locked, you&#8217;ll deadlock. This is good. I like this, just as I like crashes. I know, you think I&#8217;m crazy, but if you deadlock on your own thread, then you know you just did something bad. Most likely, you&#8217;ve called out of a function when locked to another function that ends up needing the same resource.</p>

<p>Most people, when confronted with this, switch to recursive locks. Problem solved, right? Wrong. You&#8217;ve just opened yourself up to a world of hurt, mostly due to what I said above. So what do you do? Well, what I typically do is split the function into two. Consider:</p>

<pre><code>// Some public API
void IncrementCounter()
{
    Lock();
    fCounter++;
    Unlock();
}

// Another public API
void MyFunction()
{
    Lock();
    // do some magic that requires us to increment the counter
    IncrementCounter(); // BAD: DEADLOCK!!
    Unlock();
}
</code></pre>

<p>So here we have a public function that wants to call another public function, but both of them want to lock. What I end up doing is just creating an internal function.</p>

<pre><code>void IncrementCounter()
{
    Lock();
    IncrementCounterWhileLocked();
    Unlock();
}

void MyFunction()
{
    Lock();
    IncrementCounterWhileLocked();
    Unlock();
}

void IncrementCounterWhileLocked()
{
    fCounter++;
}
</code></pre>

<p>That&#8217;s it. So basically, put the locks on the outermost (public) layer and do whatever you need to while locked on the internal layer. Yes, it&#8217;s more typing, but it&#8217;s really clarifies exactly what is going on.</p>

<p>The other thing about non-recursive locks like <code>pthread_mutex</code> is that is also forces the next two points on you, which you probably would want to do anyway.</p>

<h2>2. Keep it short and sweet</h2>

<p>You should hold your locks for as short a period of time as is necessary or practical. Using a non-recursive lock helps to enforce this rule. This is convenient since contention will be reduced. On the other hand, don&#8217;t go insane and lock every little thing. Make your locks coarse-grained enough to avoid many trips to the kernel via locking, but fine-grained enough to know that contention is low between threads so they aren&#8217;t running choppily.</p>

<h2>3. Call out when locked, go to jail</h2>

<p>Never, ever lock a mutex and then call out to some other function (unless it&#8217;s some other utility function on the same object that expects the resource to be locked). This is a deadlock waiting to happen, as that callout might end up calling something that also wants that lock. Now you&#8217;re deadlocked. Use of recursive locks over large bodies of code almost always makes this a certainty to occur.</p>

<p>So you should never do this:</p>

<pre><code>void MyFunction()
{
    Lock();

    // ... do whatever work ...

    (*fCallback)(); // UNSAFE, could even call MyFunction again!

    // ... more work ...

    Unlock();
}
</code></pre>

<p>But instead, do this:</p>

<pre><code>void MyFunction()
{
    Lock();
    // ... do whatever work ...
    Unlock();

    (*fCallback)(); // OK

    Lock();
    // ... more work...
    Unlock();
}
</code></pre>

<p><em>(As a side note, it is fine to use a recursive lock if you follow 2 &amp; 3 religiously and can guarantee correctness, as then the locality of the locks should make things obvious where problem are when there is a problem. But I still prefer non-recursive. It forces you to get it right, and enough can already go wrong with threaded programming.)</em></p>

<p>My original document also had notes about other topics, but they were more specific to our project. I think the above has universal relevance, however. As I originally mentioned, our project was violation all three rules, but I&#8217;m pretty sure the root cause was #1. All other evil tends to stem from there.</p>

<p>I think if you follow these three rules, you&#8217;ll take a lot of the guesswork out about what&#8217;s locked when, and you&#8217;ll find problems immediately (it will just deadlock, which is typically an easy fix). This should allow you to focus on the more important issues and sidestep the nastiness that might otherwise befall you.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fieryrobot.com/blog/2008/10/14/recursive-locks-will-kill-you/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
