iOS 中的 NSTimer
前陣子在整理公司項(xiàng)目的時(shí)候,發(fā)現(xiàn)老代碼在使用 NSTimer 時(shí)出現(xiàn)了內(nèi)存泄露。然后整理了一些 NSTimer 的相關(guān)內(nèi)容。比較簡(jiǎn)單,各位見(jiàn)笑啦。
NSTimer
fire
我們先用 NSTimer 來(lái)做個(gè)簡(jiǎn)單的計(jì)時(shí)器,每隔5秒鐘在控制臺(tái)輸出 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
運(yùn)行之后確實(shí)在控制臺(tái)每隔3秒鐘輸出一次 Fire ,然而當(dāng)我們從這個(gè)界面跳轉(zhuǎn)到其他界面的時(shí)候卻發(fā)現(xiàn):控制臺(tái)還在源源不斷的輸出著 Fire 。看來(lái) Timer 并沒(méi)有停止。
- invalidate
- 既然沒(méi)有停止,那我們?cè)?nbsp;DemoViewController 的 dealloc 里加上 invalidate 的方法:
- -(void)dealloc {
- [_timer invalidate];
- NSLog(@"%@ dealloc", NSStringFromClass([self class]));
- }
再次運(yùn)行,還是沒(méi)有停止。原因是 Timer 添加到 Runloop 的時(shí)候,會(huì)被 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 又會(huì)有一個(gè)對(duì) 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.
也就是說(shuō) NSTimer 強(qiáng)引用了 self ,導(dǎo)致 self 一直不能被釋放掉,所以也就走不到 self 的 dealloc 里。
既然如此,那我們可以再加個(gè) invalidate 按鈕:
- - (IBAction)invalidateButtonPressed:(id)sender {
- [_timer invalidate];
- }
嗯這樣就可以了。(在 SOF 上有人說(shuō)該在 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 在哪個(gè)線程創(chuàng)建就要在哪個(gè)線程停止,否則會(huì)導(dǎo)致資源不能被正確的釋放。看起來(lái)各種坑還不少。
dealloc
那么問(wèn)題來(lái)了:如果我就是想讓這個(gè) NSTimer 一直輸出,直到 DemoViewController 銷(xiāo)毀了才停止,我該如何讓它停止呢?
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
問(wèn)題的關(guān)鍵就在于 self 被 NSTimer 強(qiáng)引用了,如果我們能打破這個(gè)強(qiáng)引用問(wèn)題自然而然就解決了。所以一個(gè)很簡(jiǎn)單的想法就是:weakSelf:
- __weak typeof(self) weakSelf = self;
- _timer = [NSTimer scheduledTimerWithTimeInterval:3.0f
- target:weakSelf
- selector:@selector(timerFire:)
- userInfo:nil
- repeats:YES];
然而這并沒(méi)有什么卵用,這里的 __weak 和 __strong ***的區(qū)別就是:如果在這兩行代碼執(zhí)行的期間 self 被釋放了, NSTimer 的 target 會(huì)變成 nil 。
target
既然沒(méi)辦法通過(guò) __weak 把 self 抽離出來(lái),我們可以造個(gè)假的 target 給 NSTimer 。這個(gè)假的 target 類(lèi)似于一個(gè)中間的代理人,它做的***的工作就是挺身而出接下了 NSTimer 的強(qiáng)引用。類(lèi)聲明如下:
- @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
然后我們?cè)俜庋b個(gè)假的 scheduledTimerWithTimeInterval 方法,但是在調(diào)用的時(shí)候已經(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;
- }
再次運(yùn)行,問(wèn)題解決。
block
如果能用 block 來(lái)調(diào)用 NSTimer 那豈不是更好了。我們可以這樣來(lái)實(shí)現(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 里寫(xiě)相關(guān)邏輯了:
- - (IBAction)fireButtonPressed:(id)sender {
- _timer = [HWWeakTimer scheduledTimerWithTimeInterval:3.0f block:^(id userInfo) {
- NSLog(@"%@", userInfo);
- } userInfo:@"Fire" repeats:YES];
- [_timer fire];
- }
嗯就是這樣。
More
把上面的的代碼簡(jiǎn)單的封裝到了 HWWeakTimer 中,歡迎試用。