本文主要講NSTimer。CADisplaylink請猛擊。
NSTimer創建方式有三種:
??:block方式可用為iOS(10.0)。低版本調用會崩潰。
- 方式一
[scheduledTimerWithTimeInterval:invocation:repeats:]
[scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]
[scheduledTimerWithTimeInterval:repeats:repeatsblock:]??API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
class method to create the timer and schedule it on the current run loop in the default mode.
Overview:這種方式創建會自動加入到Runloop的timerSource事件中。
注意的坑:
- 加入到Runloop的mode為
NSDefaultRunLoopMode
。而UI響應滾動事件<如滑動TableView>時的mode為UITrackingRunLoopMode
。Runloop只會有一種mode運行。如果NSTimer在主線程下,此時如果定時器響應了事件,事件會被跳過。子線程不會響應UITrackingRunLoopMode
。
坑2: 如果調用線程為子線程,需要調用[[NSRunLoop currentRunLoop]run]
來啟動子線程的Runloop。
- 方式二
[timerWithTimeInterval:invocation:repeats: ]
[timerWithTimeInterval:target:selector:userInfo:repeats: ]
[timerWithTimeInterval:repeats: block:]??API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
After creating it, you must add the timer to a run loop manually by calling the addTimer:forMode:
method of the corresponding NSRunLoop object.)
Overview:這種方式必需要調用[addTimer:forMode: ]
把timer加入到Runloop中。模式可選NSRunLoopCommonModes
和NSDefaultRunLoopMode
。
補充知識:NSDefaultRunLoopMode
和UITrackingRunLoopMode
都具備commonMode屬性。它們會自動加入NSRunLoopCommonModes
中的modeItem事件。
So:NSRunLoopCommonModes
不會受其他mode影響,一般選用這種模式。
- 方式三
[- initWithFireDate:interval:target:selector:userInfo:repeats:]
[- initWithFireDate:interval:repeats:block:] ??API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
After creating it, you must add the timer to a run loop manually by calling the addTimer:forMode:
method of the corresponding NSRunLoop object)
Overview::這種方式必需要調用[addTimer:forMode: ]
把timer加入到Runloop中。模式選擇參考方式二。
special:
- 這是-號方法。
- 可以指定FireDate。即啟動定時器時間。
匯總:
- 如果你的定時器是
repeats = YES
,那要記得在不需要timer的時候調用-invalidate
來釋放定時器。 - 需要注意定時器所在的線程。
timer不執行,看這點。
- 使用定時器需要注意創建方式,是否需要手動加入Runloop。
timer不執行,看這點。
- 需要注意加入Runloop的mode。
如果timer某次未執行,看這點。
- 如果你的token用這個,一定要注意,不然token失效就GG了。
Write In Last:
本文用到了一些Runloop知識。其實timer和runloop關系很大。推薦一個特別好的博文。記得點贊哦??。