在开发中我们经常用到定时器,iOS为我们提供了多种定时器,包括NSTimer、CADisplayLink、GCD。
NSTimer
iOS中最基本的定时器,其通过RunLoop来实现,一般情况下较为准确,但当前循环耗时操作较多时,会出现延迟问题。同时,也受所加入的RunLoop的RunLoopMode影响,如果因为创建的NSTimer
默认是被加入到了 defaultMode
,比如在一个视图里面滑动tableview,当 Runloop
的Mode
变化时,当前的 NSTimer
就不会工作,故我们使用NSTimer需要用NSRunLoopCommonModes。
创建
NSTimer *timer1 = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(timerMethod1) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
释放
定时器的释放一定要先将其终止,而后才能销毁对象。
invalidate 、timer置为nil 防止循环引用。
GCD
GCD定时器是dispatch_source_t
类型的变量,其可以实现更加精准的定时效果。