幾種常見(jiàn)的timer的實(shí)現(xiàn)方式:
1.NStimer
- init
//1.如果沒(méi)有把timer添加到RunLoop的,調(diào)用timer.fire()只會(huì)執(zhí)行一次,添加RunLoop以后 就不需要再調(diào)用timer.fire()
timer = Timer.init(timeInterval: 1, target: self, selector: #selector(timerFire), userInfo: nil, repeats: true)
//timer.fire()
//2.一般默認(rèn)是default,但是當(dāng)UI滾動(dòng)的是timer會(huì)不執(zhí)行,可設(shè)置為common
RunLoop.current.add(timer, forMode: .default)
- scheduledTimer
//也是默認(rèn)把timer添加到RunLoop的default里邊的,當(dāng)UI滾動(dòng)的是timer也會(huì)不執(zhí)行
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
print(timer)
})
- 如果沒(méi)有把
timer添加到RunLoop的,調(diào)用timer.fire()只會(huì)執(zhí)行一次,添加RunLoop以后 就不需要再調(diào)用timer.fire()- 一般默認(rèn)是
default,但是當(dāng)UI滾動(dòng)的是timer會(huì)不執(zhí)行,可設(shè)置為common, 他的準(zhǔn)確性依賴RunLoop的狀態(tài)
2.DispatchSourceTimer
// 精確 - GCD 封裝timer
// 封裝了一套GCD PRODUCER 環(huán)境
//不受UI滾動(dòng)的響應(yīng)
//初始化
gcdTimer = DispatchSource.makeTimerSource()
gcdTimer?.schedule(deadline: DispatchTime.now(), repeating: DispatchTimeInterval.seconds(1))
gcdTimer?.setEventHandler(handler: {
print("hello GCD")
})
//默認(rèn)是掛起的需要執(zhí)行resume()
gcdTimer?.resume()
- 裝了一套GCD
PRODUCER環(huán)境- 不受UI滾動(dòng)的響應(yīng),準(zhǔn)確性比較高
3.CADisplayLink
cadTimer = CADisplayLink(target: self, selector: #selector(timerFire)) cadTimer?.preferredFramesPerSecond = 1
//也是需要加入runLoop,也是會(huì)受UI滾動(dòng)影響
cadTimer?.add(to: RunLoop.current, forMode: .default)
CADisplayLink不能被繼承- 也是需要加入
runLoop,也是會(huì)受UI滾動(dòng)影響
4.RxSwift Timer
//不受UI滾動(dòng)的響應(yīng), 底層是DispatchSourceTimer的封裝
timer = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
timer.subscribe(onNext: { (num) in
print(num)
})
.disposed(by: disposeBag)
- 底層是
DispatchSourceTimer的封裝
5.實(shí)現(xiàn)方式總結(jié)
