DispatchSourceTimer crashes in deinit/dealloc

Viewed 398

I'm trying to use a DispatchSourceTimer to run a repeating timer on another thread. This code runs fine in a playground, however in my iOS app it keeps crashing either on the deinit method (or if I remove the deinit it crashes on dealloc for the thread its running on) and I can't figure out why. Is there a better way to use 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()
0 Answers
Related