<?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; iPhone</title>
	<atom:link href="http://www.fieryrobot.com/blog/category/iphone/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>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>Tweetsville</title>
		<link>http://www.fieryrobot.com/blog/2008/10/11/tweetsville/</link>
		<comments>http://www.fieryrobot.com/blog/2008/10/11/tweetsville/#comments</comments>
		<pubDate>Sat, 11 Oct 2008 17:56:23 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[iPhone]]></category>

		<guid isPermaLink="false">http://www.fieryrobot.com/blog/?p=131</guid>
		<description><![CDATA[Well, it&#8217;s been about two months since I left Yahoo! and I&#8217;ve been spending pretty much literally all my time working on an iPhone application. It&#8217;s nothing super flashy, mind you, but I feel it is the best app of its kind. I had been really disappointed with all the Twitter apps for the iPhone. [...]]]></description>
			<content:encoded><![CDATA[<p>Well, it&#8217;s been about two months since I left Yahoo! and I&#8217;ve been spending pretty much literally all my time working on an iPhone application. It&#8217;s nothing super flashy, mind you, but I feel it is the best app of its kind. I had been really disappointed with all the Twitter apps for the iPhone. Either they were too slow, or scrolling was poor, or it just didn&#8217;t work the way I did. So I set out to write the version I&#8217;d want to use. I ended up with an application called Tweetsville. I&#8217;ve been putting together a small site for it <a href="http://www.tweetsville.com">here</a>, so you can check out the features there. I also have set up a <a href="http://twitter.com/tweetsville">Twitter user</a> you can follow if you care.</p>

<p>I had three goals in mind, in this order:</p>

<ul>
<li>Totally responsive, with <a href="http://www.fieryrobot.com/blog/2008/10/01/glassy-scrolling-with-uitableview/">glassy scrolling</a>.</li>
<li>Embrace the natural aesthetics of the iPhone user experience. </li>
<li>Use the full power of the <a href="http://apiwiki.twitter.com">Twitter API</a>.</li>
</ul>

<p>It&#8217;s definitely fast and smooth (though admittedly it could be tweaked a bit more), and it looks like a real honest-to-goodness iPhone application. For whatever reason, I thought it would be ideal to do this app using as many standard (or standard-looking) controls as I could. The less custom stuff the better.</p>

<p>But the real beauty is the fact that I cache as much of your Twitter stream as I can get from the API, coupled with the depth of what you can do with this application. You can see your timeline, do direct messaging, see your favorites, history, and replies. You can also see the latest trends and do searches, including advanced searches. It is without a doubt the most powerful Twitter iPhone application I&#8217;ve seen to date. Of course, I&#8217;ve had my head in the sand for the past 8 weeks!</p>

<p>Will this application change the world? Hell, no. But I think it will definitely make a dent in the Twitter space. And it was fun, which was really my whole main point of writing it. It&#8217;s been a long while since coding was fun.</p>

<p>Even with all it does, there is still other things I&#8217;d like to do to it to improve the functionality and ease of use beyond what&#8217;s there, but there are only so many hours in the day, and I&#8217;m burnt out from coding so much. I need a vacation from my vacation!</p>

<p>The real question is: should I even charge for it? I&#8217;m currently thinking no, but man, it might really take off, and then I&#8217;ll be missing out. If I don&#8217;t charge for it, I will likely make the source publicly available. I&#8217;ve already got a subversion repository set up and ready for some sources if I do. Or there&#8217;s always code.google.com.</p>

<p>I&#8217;m hoping this will get submitted very very soon. My last build seems to be pretty stable, and I&#8217;m too paranoid to make any real changes now.</p>

<p>Wow, this would be the first thing I&#8217;ve ever written and released like this since&#8230; Aaron (if anyone remembers that). Again, wow.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fieryrobot.com/blog/2008/10/11/tweetsville/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>A Small Trick for Provisioning Profiles</title>
		<link>http://www.fieryrobot.com/blog/2008/10/10/a-small-trick-for-provisioning-profiles/</link>
		<comments>http://www.fieryrobot.com/blog/2008/10/10/a-small-trick-for-provisioning-profiles/#comments</comments>
		<pubDate>Fri, 10 Oct 2008 19:03:42 +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=123</guid>
		<description><![CDATA[As most iPhone developers know, dealing with provisioning files is a bit of a pain. Even more of a pain can be altering your profile and trying to use the altered one. Well yesterday, after having to do that two or three times, I finally figured out a bit of a clue. I was having [...]]]></description>
			<content:encoded><![CDATA[<p>As most iPhone developers know, dealing with provisioning files is a bit of a pain. Even more of a pain can be altering your profile and trying to use the altered one.</p>

<p>Well yesterday, after having to do that two or three times, I finally figured out a bit of a clue. I was having trouble making xcode see the profile. Turns out, you need to have the current target configuration set to the config you are modifying in the info panel or else it just won&#8217;t show up. Made all the difference in the world.</p>

<p>And of course I always restart xcode after installing any profiles. Install, restart xcode, then ensure your target is set to the right config, then edit the config. Booyah!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fieryrobot.com/blog/2008/10/10/a-small-trick-for-provisioning-profiles/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More Glassy Scrolling with UITableView</title>
		<link>http://www.fieryrobot.com/blog/2008/10/08/more-glassy-scrolling-with-uitableview/</link>
		<comments>http://www.fieryrobot.com/blog/2008/10/08/more-glassy-scrolling-with-uitableview/#comments</comments>
		<pubDate>Wed, 08 Oct 2008 22:52:28 +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=111</guid>
		<description><![CDATA[A few days ago I wrote about how to help make your table views scroll more smoothly. The tips and tricks in there definitely work, but I&#8217;ve just added another layer of smoothness on top of that. It&#8217;s rather heavy-handed, but I thought I&#8217;d throw it out there anyway. It starts much the same, use [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.fieryrobot.com/blog/2008/10/01/glassy-scrolling-with-uitableview/">A few days ago</a> I wrote about how to help make your table views scroll more smoothly. The tips and tricks in there definitely work, but I&#8217;ve just added another layer of smoothness on top of that. It&#8217;s rather heavy-handed, but I thought I&#8217;d throw it out there anyway.</p>

<p>It starts much the same, use a single view for your cell and do all your own drawing. The ultimate solution presented here though is to cache the whole damned view contents. Revolutionary? No. Extreme? Yes. But it&#8217;s the smoothest I&#8217;ve been able to get it for my situation. I&#8217;m not yet 100% sure I&#8217;ll ship with this thing turned on, but I think it&#8217;s a valid approach for you to explore for your own project.</p>

<p>In my case I&#8217;m slowed down a bit by database fetches, text layout, and rounded images with shadows. By only following the techniques in my last blog post on this topic it&#8217;s actually not too bad. But with this addition it&#8217;s a lot better.</p>

<p>It should be noted this should really only be used as a last resort due to the increase in memory required.</p>

<p>In order to use this method, you need to be able to uniquely identify a cell by some sort of ID (in my case it&#8217;s an NSNumber).</p>

<pre><code>- (void)drawRect:(CGRect)rect
{
    if ( !_item )
        return;

    UIImage* cached = [sImageCache objectForKey:_item.identifier];
    if ( cached == nil )
    {
        CGRect    bounds = self.bounds;

        UIGraphicsBeginImageContext(
             CGSizeMake( bounds.size.width, bounds.size.height ) );

        // DRAW CONTENT HERE

        cached = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        if ( sImageCache == nil )
             sImageCache = [[NSMutableDictionary alloc]
            initWithCapacity:1];

        [sImageCache setObject:cached forKey:_item.identifier];
    }

    [cached drawAtPoint:CGPointMake(0,0)];
}
</code></pre>

<p>This is actually more expensive to draw in two ways:</p>

<ol>
<li>It means you are drawing and then blitting, instead of just drawing.</li>
<li>The table view caches the contents of cells itself, so technically we&#8217;re buffering yet again.</li>
</ol>

<p>But the advantage is that we have the caches around for more than just the visible cells (which is all UITableView cares about). So when things scroll back into view, they&#8217;re absolutely smooth as silk.</p>

<p>This does mean that as views first load in they will be less smooth than the next time they roll into view. If the user typically only scrolls in one direction, you might not see a lot of benefit. So you could decide instead to pre-cache items ahead of where the user is. So perhaps you precache the first 20 items and after that let it cache as they are encountered.</p>

<h2>When To Dump the Cache</h2>

<p>Obviously, memory-wise this is not cheap. How much should you save? When should you flush it?</p>

<p>There are many ways to deal with this: </p>

<ol>
<li>Let the system tell you when to flush. If you get a <code>didReceiveMemoryWarning</code> call, just flush the image cache completely.</li>
<li>Cap the cache at some number of items and flush it when it gets to that size.</li>
<li>Cap the cache at some number of items and drop the oldest item when a new item needs to be added (Least Recently Used).</li>
</ol>

<p>I&#8217;m actually trying out #1 believe it or not. I also flush the cache when the view has its <code>viewWillDisappear</code> method called. Why keep it around if you&#8217;re not actively flushing.</p>

<p>Another trick is to use a timed cache. Wait for the table view to stop scrolling (possibly by listening for the <code>scrollViewDidEndScrollingAnimation</code> delegate method to be called. When called, start a 10 second timer. If the view starts scrolling again, clear the timer. This way, after 10 seconds of real non-interaction, you&#8217;ll get the chance to flush the cache. No point holding them around.</p>

<p>A timed cache was what we used in Mac OS X for menus. One of the old stand-bys for measuring &#8216;performance&#8217; was how fast the menus dropped down as you dragged back and forth in the menu bar. So we used the same basic method: on first appearance, cache the image, and from then on use the cache. And then we&#8217;d set a 20 second timer to flush the buffers so we didn&#8217;t waste memory. Since then I&#8217;ve used this technique a number of times.</p>

<p>Here&#8217;s a quick boilerplate for how you could use a timer:</p>

<pre><code>- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // the user is scrolling/dragging, we WANT the cache, don't clear it!
    [self.timer invalidate];
    self.timer = nil;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView
                  willDecelerate:(BOOL)decelerate;
{
     // if decelerating, wait until it stops first, else start the timer now.
    if ( !decelerate )
    {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:10.0
                         target:self
                         selector:@selector(flushCaches:)
                         userInfo:nil
                         repeats:NO];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView
{
    // We know for sure we're done, start the timer.
    self.timer = [NSTimer scheduledTimerWithTimeInterval:10.0
                       target:self
                       selector:@selector(flushCaches:)
                       userInfo:nil repeats:NO];
}

- (void)flushCaches:(NSTimer*)timer
{
    // FINALLY. Flush it.
    [MyFancyCellView flushCaches];
    self.timer = nil;
}
</code></pre>

<p>Anyway, there you have it. Probably the most extreme method to get ultra-smooth scrolling while still using UITableView. Use it wisely.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fieryrobot.com/blog/2008/10/08/more-glassy-scrolling-with-uitableview/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
