gpt4 book ai didi

swift - 为什么我的 NSOperation 没有取消?

转载 作者:搜寻专家 更新时间:2023-10-31 22:02:52 25 4
gpt4 key购买 nike

我有这段代码可以将 NSOperation 实例添加到队列中

let operation = NSBlockOperation()
operation.addExecutionBlock({
self.asyncMethod() { (result, error) in
if operation.cancelled {
return
}

// etc
}
})
operationQueue.addOperation(operation)

当用户离开触发上述代码的 View 时,我取消正在执行的操作

operationQueue.cancelAllOperations()

测试取消时,我 100% 确定取消在异步方法返回之前执行,因此我希望 operation.cancelled 为真。不幸的是,这并没有发生,我无法理解为什么

我在 viewWillDisappear 上执行取消

编辑

asyncMethod 包含在不同线程中运行的网络操作。这就是回调存在的原因:处理网络操作返回。网络操作在类层次结构的深处执行,但我想在根级别处理 NSOperations。

最佳答案

Calling the cancel method of this object sets the value of this property to YES. Once canceled, an operation must move to the finished state.

Canceling an operation does not actively stop the receiver’s code from executing. An operation object is responsible for calling this method periodically and stopping itself if the method returns YES.

You should always check the value of this property before doing any work towards accomplishing the operation’s task, which typically means checking it at the beginning of your custom main method. It is possible for an operation to be cancelled before it begins executing or at any time while it is executing. Therefore, checking the value at the beginning of your main method (and periodically throughout that method) lets you exit as quickly as possible when an operation is cancelled.

import Foundation

let operation1 = NSBlockOperation()
let operation2 = NSBlockOperation()
let queue = NSOperationQueue()
operation1.addExecutionBlock { () -> Void in
repeat {
usleep(10000)
print(".", terminator: "")
} while !operation1.cancelled
}
operation2.addExecutionBlock { () -> Void in
repeat {
usleep(15000)
print("-", terminator: "")
} while !operation2.cancelled
}
queue.addOperation(operation1)
queue.addOperation(operation2)
sleep(1)
queue.cancelAllOperations()

在 Playground 上试试这个简单的例子。

如果运行另一个异步代码真的很重要,试试这个

operation.addExecutionBlock({
if operation.cancelled {
return
}
self.asyncMethod() { (result, error) in


// etc
}
})

关于swift - 为什么我的 NSOperation 没有取消?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33417865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com