首页 > 解决方案 > 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()

标签: iosswift

解决方案


推荐阅读