Creating High-Level Operations

suggest change

The Foundation framework provides the Operation type, which represents a high-level object that encapsulates a portion of work that may be executed on a queue. Not only does the queue coordinate the performance of those operations, but you can also establish dependencies between operations, create cancelable operations, constrain the degree of concurrency employed by the operation queue, etc.

An Operation becomes ready to execute when all of its dependencies have finished. The isReady property then becomes true.

Create a simple non-concurrent Operation subclass:

class MyOperation: Operation {

    init(<parameters>) {
        // Do any setup work here
    }

    override func main() {
        // Perform the task
    }

}
class MyOperation: NSOperation {

    init(<parameters>) {
        // Do any setup work here
    }

    override func main() {
        // Perform the task
    }

}

Add an operation to an OperationQueue:

myQueue.addOperation(operation)

This runs the operation on that queue. A concurrent queue may run it in parallel with other operations; a serial queue will not.

Manage dependencies on an Operation****.

Dependencies define other Operations that must execute on a queue before that Operation is considered ready to execute.

operation2.addDependency(operation1)

operation2.removeDependency(operation1)

Run an Operation without a queue:

operation.start()

Dependencies will be ignored. If this is a concurrent operation, the task may still be executed concurrently if its start method offloads work to background queues.

Concurrent Operations.

If the task is itself asynchronous (for example, a URLSession data task), implement a concurrent operation. isAsynchronous should return true. start usually does setup, then main runs the task.

You must implement isExecuting and isFinished, and emit KVO for them. When execution starts, isExecuting becomes true. When the task finishes, isExecuting becomes false and isFinished becomes true. If the operation is cancelled, both isCancelled and isFinished become true. All of these properties are key-value observable.

Cancel an Operation****.

Calling cancel simply changes the isCancelled property to true. To respond to cancellation from within your own Operation subclass, you should check the value of isCancelled at least periodically within main and respond appropriately.

operation.cancel()

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents