IOSTimer的例子留個備忘

來源:互聯網
上載者:User

標籤:io   ar   os   使用   sp   for   on   div   bs   

 

1、建立一個定時器 ,以下是便利構造器方法,
+ 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

表示發送的對象,如self

 selector:(SEL)aSelector

方法選取器,在時間間隔內,選擇調用一個執行個體方法

userInfo:(id)userInfo

此參數可以為nil,當定時器失效時,由你指定的對象保留和釋放該定時器。

repeats:(BOOL)yesOrNo

當YES時,定時器會不斷迴圈直至失效或被釋放,當NO時,定時器會迴圈發送一次就失效。

 

例如:

 

 

    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、觸發(啟動)

當定時器建立完(不用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過去了.

IOSTimer的例子留個備忘

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.