NSTimer學習筆記

來源:互聯網
上載者:User

NSTimer其實是將一個監聽加入的系統的RunLoop中去,當系統runloop到如何timer條件的迴圈時,會調用timer一次,當timer執行完,也就是回呼函數執行之後,timer會再一次的將自己加入到runloop中去繼續監聽。

     
CFRunLoopTimerRef 和 NSTimer這兩個類型是可以互換的,
當我們在傳參數的時候,看到CFRunLoopTimerRef可以傳NSTimer的參數,增加強制轉化來避免編譯器的警告資訊


指定(註冊)一個timer到 RunLoops中

 

 一個timer對象只能夠被註冊到一個runloop中在同一時間,儘管在這個runloop中它能夠被添加到多個runloop中模式中去。

有以下三種方法:

  使用 scheduledTimerWithTimeInterval:invocation:repeats:
或者 scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:
這兩個類方法建立一個timer並把它指定到一個預設的runloop模式中

  使用 timerWithTimeInterval:invocation:repeats:
或者 timerWithTimeInterval:target:selector:userInfo:repeats:
這兩個類方法建立一個timer的對象,不把它知道那個到run loop. (當建立之後,你必須手動的調用NSRunLoop下對應的方法 addTimer:forMode:
去將它制定到一個runloop模式中.)

  使用 initWithFireDate:interval:target:selector:userInfo:repeats:
方法分配並建立一個NSTimer的執行個體 (當建立之後,你必須手動的調用NSRunLoop下對應的方法 addTimer:forMode:
去將它制定到一個runloop模式中.)

// 安裝timer(註冊timer)    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 5// 當函數正在調用時,及時間隔時間到了 也會忽略此次調用                                             target: self                                           selector: @selector(handleTimer:)                                           userInfo: nil                                            repeats: YES]; // 如果是NO 不重複,則timer在觸發了回呼函數調用完成之後 會自動釋放這個timer,以免timer被再一次的調用,如果是YES,則會重複調用函數,調用完函數之後,會將這個timer加到RunLoop中去,等待下一次的調用,知道使用者手動釋放timer( [timer invalidate];)。


- (void) handleTimer: (NSTimer *) timer // timer的回呼函數{    //在這裡進行處理    NSLog(@"1");    //    for (int i = 0; i <= 1000000000; ) //    {//        i++;//    } }

//    [timer invalidate]; // 這個函數將timer從當前的RunLoop中remove掉,必須在timer安裝的線程中調用這個函數。

[timer fire];// 可以通過fire這個方法去觸發timer,即使timer的firing time沒有到達




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.