1、創(chuàng)建一個定時器 ,以下是便利構造器方法,
+ scheduledTimerWithTimeInterval:invocation:repeats:
+ scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
+ timerWithTimeInterval:invocation:repeats:
+ timerWithTimeInterval:target:selector:userInfo:repeats:
注:不用scheduled方式初始化的,而scheduled的初始化方法將以默認mode直接添加到當前的runloop中.需要手動addTimer:forMode: 將timer添加到一個runloop中,
scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
預訂一個Timer,設置一個時間間隔。
表示輸入一個時間間隔對象,以秒為單位,一個>0的浮點類型的值,如果該值<0,系統會默認為0.1
target:(id)aTarget
表示發(fā)送的對象,如self
selector:(SEL)aSelector
方法選擇器,在時間間隔內,選擇調用一個實例方法
userInfo:(id)userInfo
此參數可以為nil,當定時器失效時,由你指定的對象保留和釋放該定時器。
repeats:(BOOL)yesOrNo
當YES時,定時器會不斷循環(huán)直至失效或被釋放,當NO時,定時器會循環(huán)發(fā)送一次就失效。
例如:
NSTimer *showTimer = [NSTimer scheduledTimerWithTimeInterval:timer target:selfselector:@selector(PRess:) userInfo:nil repeats:NO];
NSTimer *showTimer = [NSTimer timerWithTimeInterval:4.0target:self selector:@selector(Press:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop]addTimer:showTimer forMode:NSDefaultRunLoopMode];
– initWithFireDate:interval:target:selector:userInfo:repeats:
2、觸發(fā)(啟動)
當定時器創(chuàng)建完(不用scheduled的,添加到runloop中后,該定時器將在初始化時指定的timeInterval秒后自動觸發(fā)。
可以使用-(void)fire;方法來立即觸發(fā)該定時器;
注: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.
在重復執(zhí)行的定時器中調用此方法后立即觸發(fā)該定時器,但不會中斷其之前的執(zhí)行計劃;
在不重復執(zhí)行的定時器中調用此方法,立即觸發(fā)后,就會使這個定時器失效。
3、停止
- (void)invalidate;
這個是唯一一個可以將計時器從runloop中移出的方法。
注:
NSTimer可以精確到50-100毫秒.
NSTimer不是絕對準確的,而且中間耗時或阻塞錯過下一個點,那么下一個點就pass過去了.
新聞熱點
疑難解答