
本文為投稿文章,作者:yohunl
目錄
這是我們最熟悉的一種寫法:
@property (nonatomic, strong) NSTimer *animationTimer;
self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(animationTimerDidFired:)
userInfo:nil
repeats:YES];使用 scheduledTimerWithTimeInterval: 時,Timer 會被加入「當前執行緒」的 Run Loop,模式是預設的 NSDefaultRunLoopMode。若當前執行緒就是主線程(UI 線程),某些 UI 事件(例如 UIScrollView 的拖動)會把 Run Loop 切換成 NSEventTrackingRunLoopMode,此模式下 NSDefaultRunLoopMode 中註冊的事件不會被觸發——也就是說,這時 Timer 就停止動作了。
可以加一個 UICollectionView,滑動它並觀察定時器方法的列印:
2016-01-27 11:41:59.770 enter timer 2016-01-27 11:42:00.339 enter timer 2016-01-27 11:42:01.338 enter timer 2016-01-27 11:42:02.338 enter timer 2016-01-27 11:42:03.338 enter timer 2016-01-27 11:42:15.150 enter timer 2016-01-27 11:42:15.338 enter timer
可以看到 03.338 到 15.150 之間有一段空白,正是滑動期間定時器沒有觸發。
要讓 Timer 不受 UI 干擾,得手動建立 Timer,再用 NSRunLoop 的 addTimer:forMode: 以指定模式加入 Run Loop。這裡使用的 NSRunLoopCommonModes 等效於 NSDefaultRunLoopMode 與 NSEventTrackingRunLoopMode 的集合:
self.animationTimer = [NSTimer timerWithTimeInterval:1
target:self
selector:@selector(animationTimerDidFired:)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.animationTimer forMode:NSRunLoopCommonModes];這樣無論是否正在滑動,定時器都會照常運作。
上面的寫法無論怎麼改都在主線程上跑。若要在其他執行緒跑,可以這樣做:
// 建立並啟動新執行緒
NSThread *thread = [[NSThread alloc] initWithTarget:self
selector:@selector(newThread)
object:nil];
[thread start];
- (void)newThread {
@autoreleasepool {
// 在當前 Run Loop 中加入 timer(NSDefaultRunLoopMode)
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(animationTimerDidFired:)
userInfo:nil
repeats:YES];
// 啟動該執行緒的 Run Loop
[[NSRunLoop currentRunLoop] run];
}
}注意:因為開了新執行緒,定時器回呼中若要操作 UI,仍需切回主線程。
uint64_t interval = 1 * NSEC_PER_SEC;
// 建立專門執行 timer 回呼的 GCD 佇列
dispatch_queue_t queue = dispatch_queue_create("timerQueue", 0);
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
// 設定 timer 參數
dispatch_source_set_timer(_timer, dispatch_time(DISPATCH_TIME_NOW, 0), interval, 0);
// 設定回呼
dispatch_source_set_event_handler(_timer, ^{
NSLog(@"Timer %@", [NSThread currentThread]);
});
dispatch_resume(_timer); // dispatch source 預設為 Suspended,需 resume 才會啟動其中 dispatch_source_set_timer 的最後一個參數是 leeway,用來告訴系統你對精準度的要求。所有計時器都不保證 100% 準確,這個參數表達「可容忍的誤差」:希望每 5 秒觸發且越準越好就傳 0;若是檢查 email 這類週期性任務,每 10 分鐘一次即可,就可以傳 60,讓系統有更大的合併與省電空間。它的意義在於降低整體資源消耗。
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
NSLog(@"dispatch_after enter timer");
});- (void)dispatechAfterStyle {
__weak typeof(self) wself = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
NSLog(@"dispatch_after enter timer, thread = %@", [NSThread currentThread]);
[wself dispatechAfterStyle];
});
}MSWeakTimer 用 GCD 實作了一個弱引用的 timer。核心思路是引入一個中間物件,讓 timer 強引用這個中間物件,而中間物件弱引用真正的目標:
NSString *privateQueueName =
[NSString stringWithFormat:@"com.mindsnacks.msweaktimer.%p", self];
self.privateSerialQueue =
dispatch_queue_create([privateQueueName cStringUsingEncoding:NSASCIIStringEncoding],
DISPATCH_QUEUE_SERIAL);
dispatch_set_target_queue(self.privateSerialQueue, dispatchQueue);
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,
self.privateSerialQueue);
- (void)resetTimerProperties {
int64_t intervalInNanoseconds = (int64_t)(self.timeInterval * NSEC_PER_SEC);
int64_t toleranceInNanoseconds = (int64_t)(self.tolerance * NSEC_PER_SEC);
dispatch_source_set_timer(self.timer,
dispatch_time(DISPATCH_TIME_NOW, intervalInNanoseconds),
(uint64_t)intervalInNanoseconds,
toleranceInNanoseconds);
}
- (void)schedule {
[self resetTimerProperties];
__weak MSWeakTimer *weakSelf = self;
dispatch_source_set_event_handler(self.timer, ^{
[weakSelf timerFired];
});
dispatch_resume(self.timer);
}值得注意的兩點:一是 dispatch_set_target_queue 把佇列的實際執行調度交給指定的佇列;二是它大量使用原子操作,因為作者需要在多執行緒環境下安全地切換定時器的開關。
if (OSAtomicAnd32OrigBarrier(1, _timerFlags.timerIsInvalidated))
if (!OSAtomicTestAndSet(7, _timerFlags.timerIsInvalidated)) {
dispatch_source_t timer = self.timer;
dispatch_async(self.privateSerialQueue, ^{
dispatch_source_cancel(timer);
ms_release_gcd_object(timer);
});
}其中用來存放旗標的結構體:
struct {
uint32_t timerIsInvalidated;
} _timerFlags;之所以用結構體而非單一 uint32_t 變數,是為了後續擴充其他旗標時能保持記憶體布局穩定,值得細讀。
由於下面這段程式碼:
self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(animationTimerDidFired:)
userInfo:nil
repeats:YES];timer 會強引用 self,而 self 又強引用 animationTimer,形成循環引用。若不手動讓 timer 失效,這個 VC 永遠無法釋放——特別是當它是被 push 進來的時候,pop 之後依然存在。
解法有以下幾種。
解法一:改用 MSWeakTimer 這類 GCD 弱引用定時器。
解法二:在 viewWillDisappear 中讓 timer 失效。
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[_animationTimer invalidate];
}有人會問:直接在 dealloc 中 invalidate 不行嗎?
-(void)dealloc {
[_animationTimer invalidate];
}很遺憾不行——既然已經循環引用,VC 根本進不了 dealloc。而在 viewWillDisappear 中失效雖然能解決洩漏,卻未必符合需求:當這個 VC 再 push 一個新頁面時,它本身並未釋放,按理 timer 不該被停掉;若要在 viewWillAppear 中重建,又得額外加一個旗標記錄「上次是否啟動過」,反而更麻煩。
解法三:傳入弱引用——但這招對 NSTimer 無效。
我們用 block 時習慣這樣避免循環引用:
__weak typeof(self) weakSelf = self;
self.myblock = ^(NSInteger i) {
[weakSelf view];
};於是直覺上會寫成:
__weak typeof(self) wself = self;
self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:wself
selector:@selector(animationTimerDidFired:)
userInfo:nil
repeats:YES];但這沒有用。block 是「捕獲變數」,它複製的是變數本身,在 block 的記憶體區域中相當於宣告了一個 __weak 變數並赋值,並未改變物件的持有計數,所以有效。而 NSTimer 不同——查 timerWithTimeInterval:target:selector:userInfo:repeats: 的文件會發現:The timer maintains a strong reference to this object until it (the timer) is invalidated。也就是說,內部大約是 __strong strongSelf = wself,把弱引用強引用了一次,最終仍是強引用,效果等同直接傳 self。
解法四:引入一個中間物件(如 YYWeakProxy),由它弱引用 self,再把中間物件交給 timer。
@interface YYWeakProxy : NSProxy
@property (nonatomic, weak, readonly) id target;
- (instancetype)initWithTarget:(id)target;
+ (instancetype)proxyWithTarget:(id)target;
@end
@implementation YYWeakProxy
- (instancetype)initWithTarget:(id)target {
_target = target;
return self;
}
+ (instancetype)proxyWithTarget:(id)target {
return [[YYWeakProxy alloc] initWithTarget:target];
}
// 無法識別的訊息一律轉發給 _target
- (id)forwardingTargetForSelector:(SEL)selector {
return _target;
}
// 但這兩個方法仍需實作:_target 是弱引用,可能已被釋放,
// 此時 forwardingTargetForSelector 會回傳 nil,
// 若未實作 methodSignatureForSelector / forwardInvocation 就會直接 crash
- (void)forwardInvocation:(NSInvocation *)invocation {
void *null = NULL;
[invocation setReturnValue:&null];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
return [NSObject instanceMethodSignatureForSelector:@selector(init)];
}
@end使用時只需把 target 換成 proxy:
self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:[YYWeakProxy proxyWithTarget:self]
selector:@selector(animationTimerDidFired:)
userInfo:nil
repeats:YES];實作中還轉發了 respondsToSelector:、isEqual:、hash、class、isKindOfClass:、conformsToProtocol:、description 等常用方法,讓 proxy 的行為盡量貼近原物件。
解法五:用 block 封裝 NSTimer。
@interface NSTimer (XXBlocksSupport)
+ (NSTimer *)xx_scheduledTimerWithTimeInterval:(NSTimeInterval)interval
block:(void (^)())block
repeats:(BOOL)repeats;
@end
@implementation NSTimer (XXBlocksSupport)
+ (NSTimer *)xx_scheduledTimerWithTimeInterval:(NSTimeInterval)interval
block:(void (^)())block
repeats:(BOOL)repeats {
return [self scheduledTimerWithTimeInterval:interval
target:self
selector:@selector(xx_blockInvoke:)
userInfo:[block copy]
repeats:repeats];
}
+ (void)xx_blockInvoke:(NSTimer *)timer {
void (^)block() = timer.userInfo;
if (block) {
block();
}
}
@end注意:這裡 timer 的 target 是 NSTimer 類物件本身。類物件是單例,不需要回收,因此雖形成循環引用也不會造成問題。但要留意 block 本身可能產生的間接循環引用——解法一樣簡單:在 block 內改用 weak 變數即可。