ios - DispatchSourceTimer 在 deinit/dealloc 中崩溃
问题描述
我正在尝试使用 DispatchSourceTimer 在另一个线程上运行重复计时器。这段代码在操场上运行良好,但是在我的 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()
解决方案
推荐阅读
- xamarin - 为各种页面添加 Shell 导航模板 Xamarin.Forms Shell
- angular - 从 Angular 到 Docker 引擎 API 的 HTTP 请求(进度输出 - 拉取图像)
- r - 使用 flextable 和官员库向表格添加标题
- java - 通过 LinkedList 在 JSP 中打印名称而不是按顺序打印
- php - Mockery\Exception\NoMatchingExpectationException:没有为 Mockery_1_::make 找到匹配的处理程序
- r - 如何使用带列范围的箱形图
- vue.js - 如何在 Vuex 中执行下一个操作之前等待状态更改
- python - imshow 和轮廓的颜色条重叠
- spring-mvc - 路径变量不会绑定到控制器方法参数对象属性
- java - 在 Tomcat 9 中运行 JAVA 13 JAX-RS 项目的问题