Monday December 05, 2011

✦ When GCD Isn't The Best Abstraction

While browsing Mugunth Kumar’s new MKNetworkKit network library, I came across this observation that got me thinking:

I purposefully didn’t use GCD because network operations need to be stopped and prioritized at will. GCD, while more efficient than NSOperationQueue cannot do this. I would recommend not to use GCD based queues for your network operations.

Grand Central Dispatch is an amazing piece of open source by Apple. With it you encapsulate “tasks” as simple blocks of code and run them in special queues. These queues can be concurrent or parallel and they can run on any number of threads. You get a lot of sensible defaults out of the box and there’s good customization if you want to queue things up in a custom way. Overall, it’s a very nice simplification of the standard threading model available on Unix.

The problems start when you want to treat these “tasks” as smarter encapsulations that you can start, stop, restart, or even save and try again later. That’s where using Apple’s NSOperation and NSOperationQueue still makes sense. Mugunth’s nifty new networking library offers the option to save a network operation to disk if it fails. Later, when the app is launched and has a network connection, it will automatically retry.1

Technically, you could still use GCD and just wrap the control of it in an NSOperation. And I wouldn’t be surprised if Apple reimplements NSOperationQueue using GCD. Just remember that you don’t have to reinvent the wheel if you want to encapsulate your “tasks” as objects. NSOperation is still just as robust as it ever was.

Updated Dec 6, 2011 1:00pm

As many kindly pointed out to me, Apple has already converted NSOperationQueues to use GCD under the hood, but only on Mac OSX.

  1. Mugunth’s library has a lot of other nify features, too. I’d recommend checking it out. It’s goal is to be slim and simple, like AFNetworking.