-
Notifications
You must be signed in to change notification settings - Fork 134
MyFirstOperation
Creating a custom operation is easy. Here is a simple example.
import Operations
class MyFirstOperation: Operation {
override func execute() {
print("Hello World")
finish()
}
}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.
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:
- Subclass
Operation - Override
execute(), but do not callsuper.execute(). - Always call
finish()when the work is complete. This could be done asynchronously. - 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.
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()
}
}NSOperation has a name property. It can be handy to set this for debugging purposes.
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.
- Operation
- Block Operation
- Composed Operation
- Gated Operation
- Delay Operation
- Group Operation
- URLSessionTask Operation
- Reachable Operation
- Repeated Operation
- Retry Operation
- CloudKit Operation
- Alert Operation
- UI Operation
- Location Operations
- Webpage Operations
- OpenInSafari Operations
- Condition
- Block Condition
- Composed Condition
- Not Condition
- Silent Condition
- Mutually Exclusive
- No Failed Dependencies Condition
- Remote Notification Condition
- User Confirmation Condition
- User Notification Condition