iOS 中的 NSTimer
前陣子在整理公司項目的時候,發(fā)現(xiàn)老代碼在使用 NSTimer 時出現(xiàn)了內(nèi)存泄露。然后整理了一些 NSTimer 的相關(guān)內(nèi)容。比較簡單,各位見笑啦。
NSTimer
fire
我們先用 NSTimer 來做個簡單的計時器,每隔5秒鐘在控制臺輸出 Fire 。比較想當(dāng)然的做法是這樣的:
- @interface DetailViewController ()
- @property (nonatomic, weak) NSTimer *timer;
- @end
- @implementation DetailViewController
- - (IBAction)fireButtonPressed:(id)sender {
- _timer = [NSTimer scheduledTimerWithTimeInterval:3.0f
- target:self
- selector:@selector(timerFire:)
- userInfo:nil
- repeats:YES];
- [_timer fire];
- }
- -(void)timerFire:(id)userinfo {
- NSLog(@"Fire");
- }
- @end
運行之后確實在控制臺每隔3秒鐘輸出一次 Fire ,然而當(dāng)我們從這個界面跳轉(zhuǎn)到其他界面的時候卻發(fā)現(xiàn):控制臺還在源源不斷的輸出著 Fire ??磥?Timer 并沒有停止。
- invalidate
- 既然沒有停止,那我們在 DemoViewController 的 dealloc 里加上 invalidate 的方法:
- -(void)dealloc {
- [_timer invalidate];
- NSLog(@"%@ dealloc", NSStringFromClass([self class]));
- }
再次運行,還是沒有停止。原因是 Timer 添加到 Runloop 的時候,會被 Runloop 強(qiáng)引用:
- Note in particular that run loops maintain strong references to their timers, so you don’t have to maintain your own strong reference to a timer after you have added it to a run loop.
然后 Timer 又會有一個對 Target 的強(qiáng)引用(也就是 self ):
- Target is the object to which to send the message specified by aSelector when the timer fires. The timer maintains a strong reference to target until it (the timer) is invalidated.
也就是說 NSTimer 強(qiáng)引用了 self ,導(dǎo)致 self 一直不能被釋放掉,所以也就走不到 self 的 dealloc 里。
既然如此,那我們可以再加個 invalidate 按鈕:
- - (IBAction)invalidateButtonPressed:(id)sender {
- [_timer invalidate];
- }
嗯這樣就可以了。(在 SOF 上有人說該在 invalidate 之后執(zhí)行 _timer = nil ,未能理解為什么,如果你知道原因可以告訴我:)
在 invalidate 方法的文檔里還有這這樣一段話:
- You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.
NSTimer 在哪個線程創(chuàng)建就要在哪個線程停止,否則會導(dǎo)致資源不能被正確的釋放。看起來各種坑還不少。
dealloc
那么問題來了:如果我就是想讓這個 NSTimer 一直輸出,直到 DemoViewController 銷毀了才停止,我該如何讓它停止呢?
NSTimer 被 Runloop 強(qiáng)引用了,如果要釋放就要調(diào)用 invalidate 方法。
但是我想在 DemoViewController 的 dealloc 里調(diào)用 invalidate 方法,但是 self 被 NSTimer 強(qiáng)引用了。
所以我還是要釋放 NSTimer 先,然而不調(diào)用 invalidate 方法就不能釋放它。
然而你不進(jìn)入到 dealloc 方法里我又不能調(diào)用 invalidate 方法。
嗯…
HWWeakTimer
weakSelf
問題的關(guān)鍵就在于 self 被 NSTimer 強(qiáng)引用了,如果我們能打破這個強(qiáng)引用問題自然而然就解決了。所以一個很簡單的想法就是:weakSelf:
- __weak typeof(self) weakSelf = self;
- _timer = [NSTimer scheduledTimerWithTimeInterval:3.0f
- target:weakSelf
- selector:@selector(timerFire:)
- userInfo:nil
- repeats:YES];
然而這并沒有什么卵用,這里的 __weak 和 __strong ***的區(qū)別就是:如果在這兩行代碼執(zhí)行的期間 self 被釋放了, NSTimer 的 target 會變成 nil 。
target
既然沒辦法通過 __weak 把 self 抽離出來,我們可以造個假的 target 給 NSTimer 。這個假的 target 類似于一個中間的代理人,它做的***的工作就是挺身而出接下了 NSTimer 的強(qiáng)引用。類聲明如下:
- @interface HWWeakTimerTarget : NSObject
- @property (nonatomic, weak) id target;
- @property (nonatomic, assign) SEL selector;
- @property (nonatomic, weak) NSTimer* timer;
- @end
- @implementation HWWeakTimerTarget
- - (void) fire:(NSTimer *)timer {
- if(self.target) {
- [self.target performSelector:self.selector withObject:timer.userInfo];
- } else {
- [self.timer invalidate];
- }
- }
- @end
然后我們再封裝個假的 scheduledTimerWithTimeInterval 方法,但是在調(diào)用的時候已經(jīng)偷梁換柱了:
- + (NSTimer *) scheduledTimerWithTimeInterval:(NSTimeInterval)interval
- target:(id)aTarget
- selector:(SEL)aSelector
- userInfo:(id)userInfo
- repeats:(BOOL)repeats {
- HWWeakTimerTarget* timerTarget = [[HWWeakTimerTarget alloc] init];
- timerTarget.target = aTarget;
- timerTarget.selector = aSelector;
- timerTarget.timer = [NSTimer scheduledTimerWithTimeInterval:interval
- target:timerTarget
- selector:@selector(fire:)
- userInfo:userInfo
- repeats:repeats];
- return timerTarget.timer;
- }
再次運行,問題解決。
block
如果能用 block 來調(diào)用 NSTimer 那豈不是更好了。我們可以這樣來實現(xiàn):
- + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval
- block:(HWTimerHandler)block
- userInfo:(id)userInfo
- repeats:(BOOL)repeats {
- return [self scheduledTimerWithTimeInterval:interval
- target:self
- selector:@selector(_timerBlockInvoke:)
- userInfo:@[[block copy], userInfo]
- repeats:repeats];
- }
- + (void)_timerBlockInvoke:(NSArray*)userInfo {
- HWTimerHandler block = userInfo[0];
- id info = userInfo[1];
- // or `!block ?: block();` @sunnyxx
- if (block) {
- block(info);
- }
- }
這樣我們就可以直接在 block 里寫相關(guān)邏輯了:
- - (IBAction)fireButtonPressed:(id)sender {
- _timer = [HWWeakTimer scheduledTimerWithTimeInterval:3.0f block:^(id userInfo) {
- NSLog(@"%@", userInfo);
- } userInfo:@"Fire" repeats:YES];
- [_timer fire];
- }
嗯就是這樣。
More
把上面的的代碼簡單的封裝到了 HWWeakTimer 中,歡迎試用。