【发布时间】:2019-02-11 03:17:35
【问题描述】:
我有一个可以运行很长时间的函数,如果可能的话,我想给它一个 10 秒的上限。我还想实现一个Cancel 按钮供用户按下。
我尝试在计算时简单地检查 var abort 的状态,但它只是继续工作。我对 Grand Central Dispatch 和 timers 不是很熟练,不知道从这里去哪里。
...
var abort = false
@objc func abortCalculations() {
abort = true
}
func calculate() {
abort = false
let _ = Timer(timeInterval: 10, target: self, selector: #selector(abortCalculations), userInfo: nil, repeats: false)
dispatchGroup.enter()
DispatchQueue.global(qos: .userInteractive).async {
while !abort {
x += 1 // for example, just something that repeats
// when this actually finishes, it leaves the dispatch group
}
}
}
...
我希望函数 calculate() 在计时器停止时完成(或者将来当用户按下按钮时)。相反,它会继续运行,并且永远不会调用函数 abortCalculations()。
【问题讨论】:
标签: ios swift xcode timer nstimer