第一種:
用CADisplayLink可以實現不停重繪。
例子:
CADisplayLink* gameTimer;
gameTimer = [CADisplayLink displayLinkWithTarget:self
selector:@selector(updateDisplay:)];
[gameTimer addToRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
第二種:
int CCApplication::run()
{
if (applicationDidFinishLaunching())
{
[[CCDirectorCaller sharedDirectorCaller] startMainLoop];//主循環開始
}
return 0;
}
繼續跟進startMainLoop函數
-(void) startMainLoop
{
// CCDirector::setAnimationInterval() is called, we should invalidate it first
[displayLink invalidate];
displayLink = nil;
// displayLink是CADisplayLink對象,target是自己,回調是coCaller
displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(doCaller:)];//看這個doCaller回調
[displayLink setFrameInterval: self.interval];//設置幀率
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];//添加到循環並啓動
}
看doCaller回調,
void CCDisplayLinkDirector::mainLoop(void)
{
if (m_bPurgeDirecotorInNextLoop)
{
m_bPurgeDirecotorInNextLoop = false;
purgeDirector();
}
else if (! m_bInvalid)
{
drawScene();// draw the scene
// release the objects
CCPoolManager::sharedPoolManager()->pop();
}
}
好,一個循環完了。最後看到CCPoolManager::sharedPoolManager()->pop();就是用來釋放對象的。
第三種:
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;