gpt4 book ai didi

ios - DispatchSourceTimer 在 deinit/dealloc 中崩溃

转载 作者:行者123 更新时间:2023-12-05 07:02:40 32 4
gpt4 key购买 nike

我正在尝试使用 DispatchSourceTimer 在另一个线程上运行重复计时器。这段代码在 Playground 上运行良好,但在我的 iOS 应用程序中,它总是在 deinit 方法上崩溃(或者如果我删除 deinit,它会在运行线程的 dealloc 上崩溃),我不知道为什么。有没有更好的方法来使用 DispatchSourceTimer?

import UIKit

class DispatchTest {
var timer: DispatchSourceTimer
var count: Int = 0
init(timeInterval: TimeInterval) {
timer = DispatchSource.makeTimerSource(flags: .strict, queue: DispatchQueue.global(qos: .default))
timer.schedule(deadline: .now() + timeInterval, repeating: timeInterval, leeway: .milliseconds(100))
}

func startTimer() {
timer.setEventHandler(handler: {[weak self] in
self?.count += 1
if let count = self?.count {
print(count)
}

})
timer.resume()
}

deinit {
timer.setEventHandler {}
timer.cancel()
}

func stopTimer() {
self.timer.cancel()
}
}

let dispatch = DispatchTest(timeInterval: 1)
dispatch.startTimer()

最佳答案

我遇到了同样的问题。仔细研究后,我在 Apple 的 Dispatch 文档中找到了答案。

https://developer.apple.com/documentation/dispatch/1452801-dispatch_suspend :

It is a programmer error to release an object that is currently suspended, because suspension implies that there is still work to be done. Therefore, always balance calls to this method with a corresponding call to dispatch_resume before disposing of the object. The behavior when releasing the last reference to a dispatch object while it is in a suspended state is undefined.

https://developer.apple.com/documentation/dispatch/1452929-dispatch_resume :

New dispatch event source objects returned by dispatch_source_create have a suspension count of 1

我从中推断出所有新的 DispatchSource 对象都开始挂起,因此如果您在释放之前没有恢复计时器,就会发生崩溃。

解决方案是确保定时器在释放前处于恢复状态。

关于ios - DispatchSourceTimer 在 deinit/dealloc 中崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63498780/

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