CADisplayLink与NSTimer不同点

CADispalyLink相关方法:

/* Create a new display link object for the main display. It will
 * invoke the method called 'sel' on 'target', the method has the
 * signature '(void)selector:(CADisplayLink *)sender'. */

+ (CADisplayLink *)displayLinkWithTarget:(id)target selector:(SEL)sel;

/* Adds the receiver to the given run-loop and mode. Unless paused, it
 * will fire every vsync until removed. Each object may only be added
 * to a single run-loop, but it may be added in multiple modes at once.
 * While added to a run-loop it will implicitly be retained. */

- (void)addToRunLoop:(NSRunLoop *)runloop forMode:(NSRunLoopMode)mode;

/* Removes the receiver from the given mode of the runloop. This will
 * implicitly release it when removed from the last mode it has been
 * registered for. */

- (void)removeFromRunLoop:(NSRunLoop *)runloop forMode:(NSRunLoopMode)mode;

/* Removes the object from all runloop modes (releasing the receiver if
 * it has been implicitly retained) and releases the 'target' object. */

- (void)invalidate;

属性:


//1/60
@property(readonly, nonatomic) CFTimeInterval duration;

//是否启动,YES:暂停;初始值为false
@property(getter=isPaused, nonatomic) BOOL paused;

//标识间隔多少帧调用一次selector方法,默认值是1,即每帧都调用一次;屏幕帧率60(1秒刷新屏幕60次),如果设为2,则一秒回调60/2 = 30次
@property(nonatomic) NSInteger frameInterval
//启动CADisplayLink
CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkTriggered)];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
//取消CADisplayLink
[displayLink invalidate]

CADisplayLink 对象一旦加入 Runloop 中,则会在屏幕需要刷新时回调 selector。如果要暂停对 selector 的调用,可以把 paused 属性设置为 YES 来实现。当不再使用 CADisplayLink 时,需要调用 invalidate 方法从所有的 Runloop 中将其移除。

CADisplaylink 与 NSTimer 非常类似,都可以以一定的时间间隔触发回调 selector,不同点在于 CADisplaylink 的时间间隔是与屏幕的刷新频率相关联的,这一点决定了 CADisplaylink 的应用多与显示有关。

iOS设备的刷新频率事60HZ也就是每秒60次。那么每一次刷新的时间就是1/60秒 大概16.7毫秒。当我们的frameInterval值为1的时候我们需要保证的是 CADisplayLink调用的`target`的函数计算时间不应该大于 16.7否则就会出现严重的丢帧现象。

iOS设备的屏幕刷新频率是固定的,CADisplayLink在正常情况下会在每次刷新结束都被调用,精确度相当高。NSTimer的精确度就显得低了点,比如NSTimer的触发时间到的时候,runloop如果在阻塞状态,触发时间就会推迟到下一个runloop周期。并且 NSTimer新增了tolerance属性,让用户可以设置可以容忍的触发的时间的延迟范围。

CADisplayLink使用场合相对专一,适合做UI的不停重绘,比如自定义动画引擎或者视频播放的渲染。NSTimer的使用范围要广泛的多,各种需要单次或者循环定时处理的任务都可以使用。在UI相关的动画或者显示内容使用 CADisplayLink比起用NSTimer的好处就是我们不需要在格外关心屏幕的刷新频率了,因为它本身就是跟屏幕刷新同步的。

你可能感兴趣的:(CADisplayLink与NSTimer不同点)