此功能应该重新安排工作项的执行:
class MyClass {
var id: String?
var workItem: DispatchWorkItem?
var isDoing = false
func myFunction() {
guard let id = self.id else { return }
isDoing = true
NotificationCenter.default.post(name: MyNotification, object: nil, userInfo: ["id": id])
workItem?.cancel()
workItem = DispatchWorkItem {
self.isDoing = false
NotificationCenter.default.post(name: MyNotification, object: nil, userInfo: ["id": id])
}
if let workItem = workItem {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.seconds(10), execute: workItem)
}
}
}
它在开发中运行良好,但设计似乎很可疑,所以我问了一些基本问题:
- 可能
workItem
是 nil,如果workItem?.cancel()
在队列尝试执行workItem
? id
执行时inside可能workItem
是 nilworkItem
还是由 scoped 保留let id = self.id
?- 如果对象已被释放,
isDoing
内部workItem
是否已经被释放?换句话说,当对象被释放时,调度会发生什么?workItem
MyClass
workItem
MyClass