NSTimer timerWithTimeInterval: not working

后端 未结 4 1517
挽巷
挽巷 2020-11-28 13:21

I\'ve created a test application with timer before implementing it in my project. It was the first time I\'m using timer. But the issue is when I implemented timer using

4条回答
  •  广开言路
    2020-11-28 13:58

    As a previous answer noted schedule on the main thread, but rather than using assert, put it on the main thread:

    @objc func update() {
        ...
    }
    
    DispatchQueue.main.async {
                self.timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
            }
    

    And if async is not desired, try this:

    let schedule = {
                self.timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
            }
    
            if Thread.isMainThread {
                schedule()
            }
            else {
                DispatchQueue.main.sync {
                    schedule()
                }
            }
    

提交回复
热议问题