简体   繁体   中英

OperationQueue is not removing the operations from queue if I call cancelAllOpeartions

I have opeationqueue on which I am calling cancelAllOpeations but if i ask OpearationQueue.operationcount it is not returing me zero.

I am overriding cancel method everything is working but opertioncount is not zero.is it expected?

See Apple's API Document for the NSOperation cancel method (emphasis mine):

This method does not force your operation code to stop. Instead, it updates the object's internal flags to reflect the change in state. If the operation has already finished executing, this method has no effect. Canceling an operation that is currently in an operation queue, but not yet executing, makes it possible to remove the operation from the queue sooner than usual .

The cancel method will either mark the operation as 'ready' if it is in a queue, or mark it finished immediately if it is not in a queue. Since your operations are in a queue, this means the cancelled operations will start 'sooner'. If sub-classed correctly, your cancelled operations should immediately mark itself finished and generate its final KVO notifications. Only then will your operations be dequeued.

See also Responding to the Cancel Command for more information about cancelling custom operations.

If you need to know when the operation queue has 0 operations left in its operations array property, you might consider registering the queue's owner as an observer for the operationCount key path using KVO. Then when you are notified that the value of that property has changed, you can check to see if the value is 0 and then perform any logic required. Note that NSOperations send their KVO notifications on the thread they are operating on, which is usually going to be a background thread if they are run from an NSOperationQueue - this means that if you need to perform any UI/blocking logic, you will need to ensure it is run on the main thread.

If you decide to add an observer using KVO, make sure that you balance that by removing the observer later. In fact, if you do decide to leverage KVO, I highly suggest you digest all of the KVO programming guide and read through the KVO API docs , anything short of due-diligence when working with that framework can result in undefined behaviors, memory leaks, or even bad_access crashes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM