Skip to content
Daniel Thorpe edited this page May 15, 2016 · 1 revision

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

import Operations

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

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

To use the operation, we need to add it to an OperationQueue.

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

This is a contrived example, but the important points are:

  1. Subclass Operation
  2. Override execute(), but do not call super.execute().
  3. Always call finish() when the work is complete. This could be done asynchronously.
  4. Add operations to instances of OperationQueue.

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

Best Practices

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

class Greeter: Operation {

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

Set the name

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

Cancelling

Operation will check that it has not been cancelled before it invokes execute. However, depending on the work being done, the subclass should periodically check if it has been cancelled, and then finish accordingly. See the Cancellation page for more info.

Clone this wiki locally