Search code examples
swiftcocoansoperationqueuensblockoperation

Make BlockOperation fail so that other dependencies don't execute


In a simple case operation2 is dependent on operation1, however operation1 may fail and in this case we don't want to execute operation2

is it possible to deliver a failed execution inside the operation1 code block? so that operation1 fails to complete and operation2 never gets executed and is disposed?

let operation1 = BlockOperation {

    // do smth, which can fail

}

let operation2 = BlockOperation {

}


operation2.addDependency(operation1)

Solution

  • You have to cancel the dependent operations manually. An Operation has a dependencies array containing all the operations depending on the operation. In the place in operation1 that you detect failure, cycle through the dependencies array and call cancel() on each of the operations in the array.

    Calling cancel() is not always enough to actually cancel an operation. The general setup is that the beginning of the start() function checks the isCancelled boolean and if it's true, returns without executing the task. So the operation "executes" but doesn't do the actual work. If you've overridden start() you will have to do this yourself.

    All of this needs to be done before isFinished is set to true.