Programming Guide

MyFirstOperation

Creating a custom operation is easy. Here is a simple example.

import Operations

class MyFirstOperation: Operation {
    override func execute() {
        print("Hello World")
        finish()
    }
}

This is a contrived example, but the important points are

  1. Subclass Operation
  2. Override execute(), but do not call super.
  3. Always call finish() when the work is complete.

❗️

Finishing

If the operation does not call finish() or finishWithError() it will never complete. This might block a queue from executing subsequent operations. Any operations which are waiting on the stuck operation will not start.

Executing the operation

To execute the operation, add it to an OperaitonQueue.

let queue = OperationQueue()
let operation = MyFirstOperation()
queue.addOperation(operation)

If the queue is not suspended, operations will be executed as soon as they become ready and the queue has capacity.

Apply best practices

The operation is a class, and so object orientated programming best practices apply. For example pass known dependencies into the operation's initializer:

class Greeter: Operation {

    let personName: String
    
    init(name: String) {
        self.personName = name
        super.init()
        name = "Greeter Operation"
    }
    
    override func execute() {
        print("Hello \(personName)")
        finish()
    }
}

👍

Give your operation a name

NSOperation has a name property. It can be handy to set this for debugging purposes.

🚧

Responding to Cancellation

This example has been kept particularly simple to get some key points across. But, check out the page on cancellation for a better implementation.