NSOperations, NSOperationQueue, Oh my 😚

Taking control of your app flow once and for all.

Raul Riera
If let swift = Programming!
2 min readDec 14, 2015

--

Let’s say we need a piece of asynchronous code, I bet by now you shouted Grand Central Dispatch!. But what if I told you Apple envisioned you to use something simpler, something a little more “high level”.

NSOperation is a sane abstraction of Grand Central Dispatch. Allowing you to queue, run on multiple threads, etc. While still being able to code in something that can be read by humans.

Apps have multiple threads, multiple touches and tons of things happening at the same time.

Getting control of your app flow.

Every iOS project is different, but there is a single thing that brings them all together. Apps have multiple threads, multiple touches and tons of things happening at the same time. Keeping track of all these is difficult, this is when you start putting up “flags”, and booleans all over the place to bring some sanity back into your app.

“IsLoading, isReady”, these are terrible idioms to include in apps, and yet they are very common. I’m sure by now you watched most of the videos of WWDC 2015, but there is one in particular that tackles the problems of app flow very efficiently.

You can tell from the title that this is not a trivial concept. Using NSOperations to control things like Network Requests, UIAlert dialogs, etc. It’s a pretty clever idea, but very cumbersome to implement at first. Therefore I wanted to embrace this subject but start with something simple.

Introducing the URLSessionOperation

The problem is simple, we want to make a network request. We dust off the old “session.dataTaskWithURL”, then a little block here and a dispatch in the main queue there, now the problem is solved. What if we want to run something after this is finished and we don’t want it the completion block?. In situations like these, NSOperationQueues come to mind.

The previous snippet of code is pretty much self explanatory, two operations that will be execute one after the other. URLSessionOperation at the end of the day is a simple NSURLSessionTask wrapped in a NSOperation.

URLSessionOperation only solves the first problem, but it’s a good starting point to think about how NSOperations can be used to control the flow of an app. I suggest playing around with other things like NSOperations for parsing object, displaying UI, etc.

Where to go from here?

It might be obvious, but taking a look again at the “Advanced NSOperations” talk, as well as checking out the Sample App is a wonderful place to get started. I wouldn’t recommend taking the “operations” folder and winging it on your own app. But rather reading the source code and try to implement a simple version of those.

Something like this for example:

--

--