iOS開發-NSTimer

1、初始化

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

注:不用scheduled方式初始化的,需要手動addTimer:forMode: 將timer添加到一個runloop中。

  而scheduled的初始化方法將以默認mode直接添加到當前的runloop中.


舉例:

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(timerFired:userInfo:nil repeats:NO];

NSTimer *myTimer = [NSTimertimerWithTimeInterval:3.0 target:selfselector:@selector(timerFired:) userInfo:nilrepeats:NO];

[[NSRunLoopcurrentRunLoopaddTimer:myTimerforMode:NSDefaultRunLoopMode];

 

2、觸發(啓動)

當定時器創建完(不用scheduled的,添加到runloop中後,該定時器將在初始化時指定的timeInterval秒後自動觸發。


可以使用-(void)fire;方法來立即觸發該定時器;

注:You can use this method to fire a repeating timer without interrupting its regular firing schedule. If the timer is non-repeating, it is automatically invalidated after firing, even if its scheduled fire date has not arrived.

在重複執行的定時器中調用此方法後立即觸發該定時器,但不會中斷其之前的執行計劃;

在不重複執行的定時器中調用此方法,立即觸發後,就會使這個定時器失效。

 

3、停止

- (void)invalidate;

這個是唯一一個可以將計時器從runloop中移出的方法。

 

注:

NSTimer可以精確到50-100毫秒.

NSTimer不是絕對準確的,而且中間耗時或阻塞錯過下一個點,那麼下一個點就pass過去了.

發佈了18 篇原創文章 · 獲贊 1 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章