Building robust, reliable code with NSOperations

NSOperations are a tool provided by Apple to model small, repeatable tasks. This abstraction may seem simple, but we can use it to build all sorts of complex flows and logic.

Throughout this series of articles, you’ll learn everything you need to know in order to start using NSOperations in your own code. This means we’ll look at:

  • The basics of NSOperations and the essential base class you’ll need.
  • How to chain operations together in order to create a complex sequence of events (for example: fetch an object, then parse it, then push a View Controller)
  • How we can easily group multiple operations together to make their use more convenient (for example: creating a download + parse operation out of a download operation and a parse operation)
  • How we can integrate complete flows of UI with operations (show a wizard + create an object + save to Core Data)

My friends often joke about how I never shut up about NSOperations, and I don’t blame them. Ever since I’ve become more familiar with NSOperations, they’ve completely changed the way I develop apps. They make my apps easier to create, read, and maintain.

What’s more, I’ve slowly built myself a library of NSOperations that give me a massive head start when I start a new project.

I’m hoping you’ll get just as much out of this as I did!

1. Getting started with NSOperation and NSOperationQueue

NSOperation and NSOperationQueue aren’t complex. However, it’s vitally important to understand how they work. In this article we look at the operation lifecycle, where we hook in, and how we can start making our own!

2. Chaining a Series of NSOperations

While having a single NSOperation is nice, their true power lies in how we can compose them together. In this article, we’ll look at how we can pass data from one operation to another in order to create truly reusable pieces of code.

3. Grouping commonly used operations

You’ll quickly see that creating the same operations over and over again can become a verbose. In this article, we’ll look at how we can group commonly used operations together to keep our code nice and tidy 👌🏻

4. Integrating UI with Operations

Sometimes, it can be useful for us to include UI into our operation flows. In this article, we’ll explore how we can make this possible. We’ll wrap a complete UI flow (like an onboarding process) into an NSOperation that can be chained just like any other!

I really hope you enjoy this guide to NSOperations. If you do, you can follow me on Twitter and share it with your friends.