NSTimer學習筆記

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沒有到達





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章