一、初始化 html
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo; git
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo; github
注:不用scheduled方式初始化的,須要手動addTimer:forMode: 將timer添加到一個runloop中。 函數
而scheduled的初始化方法將以默認mode直接添加到當前的runloop中. oop
舉例: this
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO]; spa
或 code
NSTimer *myTimer = [NSTimer timerWithTimeInterval:3.0 target:selfselector:@selector(timerFired:)userInfo:nilrepeats:NO]; orm
[[NSRunLoop currentRunLoop] addTimer:myTimerforMode:NSDefaultRunLoopMode]; htm
二、觸發(啓動)
當定時器建立完(不用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.
在重複執行的定時器中調用此方法後當即觸發該定時器,但不會中斷其以前的執行計劃;
在不重複執行的定時器中調用此方法,當即觸發後,就會使這個定時器失效。
三、中止
- (void)invalidate;
這個是惟一一個能夠將計時器從runloop中移出的方法。
注:
NSTimer能夠精確到50-100毫秒.
NSTimer不是絕對準確的,並且中間耗時或阻塞錯過下一個點,那麼下一個點就pass過去了.
延時函數和Timer的使用
//延時函數: [NSThread sleepForTimeInterval:5.0]; //暫停5s. //Timer的使用: NSTimer *connectionTimer; //timer對象 //實例化timer self.connectionTimer=[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO]; [[NSRunLoop currentRunLoop]addTimer:self.connectionTimer forMode:NSDefaultRunLoopMode]; //用timer做爲延時的一種方法 do{ [[NSRunLoopcurrentRunLoop]runUntilDate:[NSDatedateWithTimeIntervalSinceNow:1.0]]; }while(!done); //timer調用函數 -(void)timerFired:(NSTimer *)timer{ done =YES; }
轉自:http://magicalboy.com/objective_c_nstimer_usage/#comment-45
[self performSelector:@selector(targetMethod:) withObject:nil afterDelay:2.0];