CADispalyLink相關(guān)方法:
/* 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;
//是否啟動(dòng)组去,YES:暫停;初始值為false
@property(getter=isPaused, nonatomic) BOOL paused;
//標(biāo)識(shí)間隔多少幀調(diào)用一次selector方法欢揖,默認(rèn)值是1岂座,即每幀都調(diào)用一次臂港;屏幕幀率60(1秒刷新屏幕60次)椒涯,如果設(shè)為2,則一秒回調(diào)60/2 = 30次
@property(nonatomic) NSInteger frameInterval
//啟動(dòng)CADisplayLink
CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkTriggered)];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
//取消CADisplayLink
[displayLink invalidate]
CADisplayLink 對(duì)象一旦加入 Runloop 中碉就,則會(huì)在屏幕需要刷新時(shí)回調(diào) selector盟广。如果要暫停對(duì) selector 的調(diào)用,可以把 paused 屬性設(shè)置為 YES 來實(shí)現(xiàn)瓮钥。當(dāng)不再使用 CADisplayLink 時(shí)筋量,需要調(diào)用 invalidate 方法從所有的 Runloop 中將其移除。
CADisplaylink 與 NSTimer 非常類似骏庸,都可以以一定的時(shí)間間隔觸發(fā)回調(diào) selector毛甲,不同點(diǎn)在于 CADisplaylink 的時(shí)間間隔是與屏幕的刷新頻率相關(guān)聯(lián)的,這一點(diǎn)決定了 CADisplaylink 的應(yīng)用多與顯示有關(guān)具被。
iOS設(shè)備的刷新頻率事60HZ也就是每秒60次玻募。那么每一次刷新的時(shí)間就是1/60秒 大概16.7毫秒。當(dāng)我們的frameInterval值為1的時(shí)候我們需要保證的是 CADisplayLink調(diào)用的`target`的函數(shù)計(jì)算時(shí)間不應(yīng)該大于 16.7否則就會(huì)出現(xiàn)嚴(yán)重的丟幀現(xiàn)象一姿。
iOS設(shè)備的屏幕刷新頻率是固定的七咧,CADisplayLink在正常情況下會(huì)在每次刷新結(jié)束都被調(diào)用,精確度相當(dāng)高叮叹。NSTimer的精確度就顯得低了點(diǎn)艾栋,比如NSTimer的觸發(fā)時(shí)間到的時(shí)候,runloop如果在阻塞狀態(tài)蛉顽,觸發(fā)時(shí)間就會(huì)推遲到下一個(gè)runloop周期蝗砾。并且 NSTimer新增了tolerance屬性,讓用戶可以設(shè)置可以容忍的觸發(fā)的時(shí)間的延遲范圍携冤。
CADisplayLink使用場合相對(duì)專一悼粮,適合做UI的不停重繪,比如自定義動(dòng)畫引擎或者視頻播放的渲染曾棕。NSTimer的使用范圍要廣泛的多扣猫,各種需要單次或者循環(huán)定時(shí)處理的任務(wù)都可以使用。在UI相關(guān)的動(dòng)畫或者顯示內(nèi)容使用 CADisplayLink比起用NSTimer的好處就是我們不需要在格外關(guān)心屏幕的刷新頻率了翘地,因?yàn)樗旧砭褪歉聊凰⑿峦降摹?/p>