NSOperations, Dependencies, and Failed Operations

I started working with CloudKit and finally started using NSOperation subclasses for most of my asynchronous files.

Be that as it may, I have two questions.

  • How can I mark an operation as unsuccessful? That is, if operation A fails, I will not start its dependent operations. Can I just mark it as isFinished? What happens to unexecuted items already in the queue?

  • What would be the recommended route if I wanted something like try, catch, finally. The ultimate goal is to have one last operation that can display some user interface with success information or report errors to the user?

+4
source share
3 answers

isFinishedmeans that your operations are completed, you can cancel the operation, but this means that your operation is canceled, and this can be done without even performing the operation, and you can check it by calling isCanceledif you need special flags of failure and success after execution NSOperationthen add a property to the subclass isFailureand check the dependent operation before execution, and cancel it if isFailure is set to true.

You can add a dependency on the operation and check the status there, and if everything is successful, just refresh the user interface in the main thread or the report and error.

Update You can save an array of dependent operations, and in case of failure you can cancel these operations.

+1
  • . . CKOperations , " ", .

  • - KVO operationCount ( Github) . , ( ), , . , , , , , , , , .

0

:

  • ( -) ,

  • The order in which you cancel the operation is important because canceling the operation allows you to start dependent operations (because the condition of the dependency has been violated).

  • To do this, you need to have variables holding each of these dependent operations so that you cancel them in the order that you intend.

Code:

var number = 0

let queue = OperationQueue()

let b = BlockOperation()
let c = BlockOperation()
let d = BlockOperation()

let a = BlockOperation {

    if number == 1 {

        //Assume number should not be 1
        //If number is 1, then it is considered as a failure

        //Cancel the remaining operations manually in the reverse order
        //Reverse order is important because if you cancelled b first, it would start c
        d.cancel()
        c.cancel()
        b.cancel()
    }
}

b.addDependency(a)
c.addDependency(b)
d.addDependency(c)

queue.addOperation(a)
queue.addOperation(b)
queue.addOperation(c)
queue.addOperation(d)
0
source

Source: https://habr.com/ru/post/1606721/


All Articles