如何获取所有计划或执行的OperationQueue并取消它

时间:2018-08-31 09:44:32

标签: ios swift nsoperationqueue nsoperation

我有一种情况,我想取消所有从多个ViewController计划或启动的NSOperationQueue。

预先感谢

1 个答案:

答案 0 :(得分:0)

让我们看一个例子

let queue = OperationQueue()

let op = BlockOperation {
    print("Operation 1 is executing")
}

let op2 = BlockOperation {
    print("Operation 2 is executing")
}

queue.addOperation(op)
queue.addOperation(op2)

如果运行此代码,您将得到结果

Operation 1 is executing
Operation 2 is executing

在添加了两个BlockOperationOperation之后,您可以通过以下方式取消它们

queue.cancelAllOperations()

您可以获得队列中的操作列表

print(queue.operations)

你会得到

[
 <NSBlockOperation 0x600000043e40 isFinished=YES isReady=YES isCancelled=NO isExecuting=NO>, 
 <NSBlockOperation 0x600000045e50 isFinished=YES isReady=YES isCancelled=NO isExecuting=NO>
]

因此,您可以看到两者都已完成,但尚未取消,但是如果我们要使用queue.cancelAllOperations()取消它们,则会得到

[
 <NSBlockOperation 0x600000043e40 isFinished=YES isReady=YES isCancelled=YES isExecuting=NO>, 
 <NSBlockOperation 0x600000045e50 isFinished=YES isReady=YES isCancelled=YES isExecuting=NO>
]