IOS 中 NSTimer和CADisplayLink的用法

IOS 中 NSTimer和CADisplayLink的用法  

    NSTimer初始化器接受調用方法邏輯之間的間隔作爲它的其中一個參數,預設一秒執行30次CADisplayLink默認每秒運行60次,通過它的frameInterval屬性改變每秒運行幀數,如設置爲2,意味CADisplayLink每隔一幀運行一次,有效的邏輯每秒運行30次。此外,NSTimer接受另一個參數是否重複,而把CADisplayLink設置爲重複(默認重複?)直到它失效。

        還有一個區別在於,NSTimer一旦初始化它就開始運行,而CADisplayLink需要將顯示鏈接添加到一個運行循環中,即用於處理系統事件的一個Cocoa Touch結構。

        NSTimer 我們通常會用在背景計算,更新一些數值資料,而如果牽涉到畫面的更新,動畫過程的演變,我們通常會用CADisplayLink。

但是要使用CADisplayLink,需要加入QuartzCore.framework及#import <QuartzCore/CADisplayLink.h>

NSTimer

@interface ViewController : UIViewController

{

    NSTimer *theTimer; //聲明

}

//使用

float theInterval = 1.0 / 30.0f;  //每秒調用30次

theTimer = [NSTimer scheduledTimerWithTimeInterval:theInterval target:self selector:@selector(MyTask) userInfo:nil repeats:YES];

//停用

[theTimer invalidate];

theTimer = nil;

CADisplayLink,需要加入QuartzCore.framework及#import <QuartzCore/CADisplayLink.h>

/*CADisplayLink 默認每秒運行60次,將它的frameInterval屬性設置爲2,意味CADisplayLink每隔一幀運行一次,有效的使遊戲邏輯每秒運行30次*/

    if(theTimer == nil)

    {

        theTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(MyTask)];

        theTimer.frameInterval = 2;

        [theTimer addToRunLoop: [NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    }

//停用

[theTimer invalidate];

theTimer = nil;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章