Codes from the Underground

Ben Coe is a software developer based in SF. He currently hacks up a storm at @attachmentsme His interests include climbing, coding, and being awesome.

(Follow Ben on Twitter, My Projects on GitHub)
Jan 15

Objective-C Designing With Blocks

I recently started doing some Objective-C development at work. Coming from a Ruby/Python/JavaScript background, I was stoked to see that Objective-C had support for blocks.

Here’s a great tutorial on the subject.

Closures are a wonderful way to handle the complexities surrounding asynchrounous I/O. Ask any Node.js nerd, they’ll attest to this fact.

I’ve been leaning on blocks heavily while building libraries for handling I/O in Objective-C. The approach I use is as follows:

  • I create a delegate class that interacts with the foundation frameworks.
  • The methods of the API exposed by the delegate accept blocks, and invoke the blocks when a series of asynchrounous actions has reached a terminal point.
  • The class interacting with the library does not need to worry about the intermediate actions being taken by the delegate, it just trusts that its block will be invoked with the appropriate response.

As an example of this methodology in action, here’s an asynchrounous IMAP client I’ve been working on:

https://github.com/bcoe/IMAPClient

The IMAP class itself is an NSStreamDelegate. When a user invokes an IMAP command, a block is provided. The delegate methods handle the specifics surrounding the asynchrounous I/O. Once an operation eventually completes, the block is invoked. Here’s the code that handles running a command:

An individual consuming the library need not worry about these specifics. They simply provide the block and trust that it will eventually be invoked with the appropriate response. Ultimately, a series of IMAP commands takes on a form resembling this:

cool, eh?

In the same vein, here’s what an API call looks like to an OAuth HTTP framework I’ve been working on:

I find this is a great way to decompose asynchrounous problems. It’s been working great for us at Attachments.me, as we build out our iOS stack.

— Ben (@benjamincoe)


  1. replore reblogged this from bencoe
  2. thezenmoment reblogged this from bencoe
  3. bencoe posted this