Calling - (void) cancelAllOperations in NSoperationQueue does not set the isCancelled NSOperation property, which is present inside the queue

I ran into a problem related to NSoperationQueue. In my code in:

-(void) viewDidLoad { //Initialisation of queue and operation. //adding operation to queue [self.operationQueue addOperation:op]; } -(void) viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.operationQueue cancelAllOperations]; } 

Thus, during the execution of my main NSOperation function, when I check the isCancelled property, it always returns NO. Infact after calling cancelAllOperation function in NSOperationQueue. eg.

 -(void)main { if(self.isCancelled) { // Never executing this block :-( } } 

For more information, I am making some network calls in my NSOperation. And when I switched to another view, then cancel AllOperation is called. And when the network response returned to my NSOperation, I check if (Self.isCancelled), and now I am in a different view (then isCancelled should set YES). but this check always fails.

+7
source share
2 answers

Your operation is added to the queue immediately after loading the view into viewDidLoad , and then the queue takes responsibility for starting the operation.

Since you cancel your operation (s) when the view disappears ( viewWillDisappear ), the operation will most likely be completed at this time. In other words, your operation is canceled after it is terminated. You can check the isExecuting property to see if the operation is active.

+1
source

Your operation probably does not work anymore and therefore cannot be undone. (Once your operation is completed, the operation queue will no longer track it, so calling cancelAllOperations do nothing.)

If the network response you expect calls a callback rather than blocking the main call, your operation will already be completed (when the main function returns). You can fix this using a "parallel" operation (see NSOperation Documents, you can specify when everything is ready, and not just automatically run when the basic information is returned) or using synchronous network calls (so the main function does not return until you really done).

+1
source

All Articles