NSTimer scheduledTimerWithTimeInterval與timerWithTimeInterval、initWithFireDate的區別


英文原文是這樣的:

A timer object can be registered in only one run loop at a time, although it can be added to multiple run loop modes within that run loop. There are three ways to create a timer:

Once scheduled on a run loop, the timer fires at the specified interval until it is invalidated. A non-repeating timer invalidates itself immediately after it fires. However, for a repeating timer, you must invalidate the timer object yourself by calling its invalidate method. Calling this method requests the removal of the timer from the current run loop; as a result, you should always call the invalidate method from the same thread on which the timer was installed. Invalidating the timer immediately disables it so that it no longer affects the run loop. The run loop then removes the timer (and the strong reference it had to the timer), either just before the invalidate method returns or at some later point. Once invalidated, timer objects cannot be reused.

 

翻譯過來大體是這樣的:

有三種方法來創建一個定時器

1.使用scheduledTimerWithTimeInterval

類方法創建計時器和進度上當前運行循環在默認模式(NSDefaultRunLoopMode)

2.使用timerWithTimerInterval

類方法創建計時器對象沒有調度運行循環(RunLoop)

在創建它,必須手動添加計時器運行循環,通過調用adddTimer:forMode:方法相應的NSRunLoop對象

3.使用initWithFireDate

在創建它,必須手動添加計時器運行循環,通過使用addTimer:forMode:方法相應的NSRunLoop對象

 

1.

- (void)execute {
    NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}

2.

- (void)execute {
    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:YES];
    //為什么在主線程不需要這句run,那是因為主線程有RunLoop而且已經啟動
    [[NSRunLoop currentRunLoop] run];
}

 

這兩個代碼效果是一樣的,scheduledTimerWithTimeInterval相當於timerWithTimeInterval的兩句。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM