记录几种swift常用的定时器方式;
1、Timer
跟OC的NSTimer一样,有两种创建方式
var timer: Timer?
(1) timer = Timer.init(timeInterval: 1, target: self, selector: #selector(timerCountDown), userInfo: nil, repeats: true)
RunLoop.current.add(timer!, forMode: .common)
(2) timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in
print(timer!)
})
// 第一种方式必须加入当前的runloop,定时器才会起作用,第二种默认加入default模式
销毁timer
timer?.invalidate()
timer = nil
2、DispatchSourceTimer
一种GCD 封装的timer,不受scrollview滑动影响
var gcdTimer: DispatchSourceTimer?
gcdTimer = DispatchSource.makeTimerSource()
gcdTimer?.schedule(deadline: DispatchTime.now(), repeating: DispatchTimeInterval.seconds(1))
gcdTimer?.setEventHandler(handler: {
print("hello GCD")
})
gcdTimer?.resume()
暂停计时器
gcdTimer?.suspend()
继续
gcdTimer?.resume()
停止、销毁计时器
gcdTimer?.cancel()
gcdTimer = nil
3、CADisplayLink
var cadTimer: CADisplayLink?
cadTimer = CADisplayLink(target: self, selector: #selector(timerFire))
cadTimer?.preferredFramesPerSecond = 1
cadTimer?.add(to: RunLoop.current, forMode: .common)
必须加入当前的runloop,定时器才会起作用
销毁定时器
cadTimer?.invalidate()
cadTimer = nil
4、RXSwift里面的定时器
不受scrollView滑动影响
var timer: Observable<Int>!
let disposeBag = DisposeBag()
timer = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
timer.subscribe(onNext: { (num) in
print(num)
}).disposed(by: disposeBag)