美文网首页
IOS开发中常用的计时器

IOS开发中常用的计时器

作者: 恍然如梦_b700 | 来源:发表于2020-06-08 13:10 被阅读0次

Timer

需要注意,Timer需要加入RunLoop才会开启,并且设置RunLoop.Mode = .common才不会受UI事件影响,但是加入到.common有可能会出现一些问题,比如NSTimer的触发时间到的时候,runloop如果在阻塞状态,触发时间就会推迟到下一个runloop周期,所以NSTimer的精确度低了点。

GCD

我一般使用GCD来计时,因为精准度较高。

CADisplayLink

不是很常用,CADisplayLink是一个定时器对象,它可以让你与屏幕刷新频率相同的速率来刷新你的视图。就说CADisplayLink是用于同步屏幕刷新频率的计时器。
同样需要添加到runloop,不然不会被触发

 //MARK: - 计时器的实现种类
    func testTimer(){
        timer = Timer.init(timeInterval: 1, target: self, selector: #selector(timerFire), userInfo: nil, repeats: true)
        RunLoop.current.add(timer, forMode: .common)
   
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
            print(timer)
        })
    }
    
    // 精确 - GCD 封装timer
    // 封装了一套GCD PRODUCER 环境
    func testGCD(){
        gcdTimer = DispatchSource.makeTimerSource()
        gcdTimer?.schedule(deadline: DispatchTime.now(), repeating: DispatchTimeInterval.seconds(1))
        gcdTimer?.setEventHandler(handler: {
            print("hello GCD")
        })
        gcdTimer?.resume()
        gcdTimer?.suspend()
        gcdTimer?.cancel()
        gcdTimer = nil

    }
    
    func textCAD() {
        cadTimer = CADisplayLink(target: self, selector: #selector(timerFire))
        cadTimer?.preferredFramesPerSecond = 1
        cadTimer?.add(to: RunLoop.current, forMode: .default)
        // cadTimer?.isPaused = true
    }

相关文章

网友评论

      本文标题:IOS开发中常用的计时器

      本文链接:https://www.haomeiwen.com/subject/axkltktx.html