NSOperations, NSOperationQueue, Oh my đ
Taking control of your app flow once and for all.
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.
let operation = URLSessionOperation(url: someURL, completion: completion)let otherOperation = URLSessionOperation(url: otherURL, completion: completion)otherOperation.addDependency(operation)
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: