您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

徹底搞懂 iOS 中的 NSTimer:從內存洩露到優雅封裝

編輯:iOS 相關資訊

前陣子梳理公司老項目的時候,發現一段用了很久的 NSTimer 代碼存在明顯的內存洩露。順著這條線索查下去,把 NSTimer 的引用關係、停止時機以及常見的封裝方案都重新捋了一遍。內容不算深,但坑確實不少,整理出來給大家做個參考。

一、最直覺的寫法:fire

先用 NSTimer 做一個最簡單的計時器,每隔幾秒在控制台打印一次 Fire。多數人第一反應大概都是這樣寫:

@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 依然源源不斷。定時器根本沒有停下來。

二、加 invalidate 為什麼沒用

既然沒停,那就在 dealloc 裡補一刀:

- (void)dealloc {
    [_timer invalidate];
    NSLog(@"%@ dealloc", NSStringFromClass([self class]));
}

再跑一次,還是停不下來,而且 dealloc 也沒有被調用。原因藏在兩段官方文檔裡。

第一,Runloop 會對它管理的 timer 持有強引用:

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 持有強引用,直到它被 invalidate 為止:

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.

於是一個閉環出現了:Runloop 強引用 timer,timer 強引用 self,self 無法釋放,dealloc 永遠不會執行,invalidate 也就永遠沒有機會被調用。

如果我們手動加一個「停止」按鈕,問題立刻緩解:

- (IBAction)invalidateButtonPressed:(id)sender {
    [_timer invalidate];
}

但這只是把責任推給了使用者,並沒有真正解決問題。(Stack Overflow 上有人提到 invalidate 之後還應該把 `_timer = nil`,關於這一點我沒能完全理解其必要性,如果你知道原因歡迎指教。)

文檔裡還有一句容易被忽略的提醒:

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 在哪個線程創建,就必須在哪個線程銷毀,否則相關資源無法被正確回收。

三、一個死循環般的困境

把上面的結論串起來,需求變成了一個看似無解的循環:

  • timer 被 Runloop 強引用,要釋放它必須調用 invalidate。

  • 我們希望在 dealloc 裡調用 invalidate,但 self 正被 timer 強引用。

  • 也就是說必须先釋放 timer,而不調用 invalidate 就無法釋放它。

  • 而不進入 dealloc,就沒有機會調用 invalidate。

四、方案一:weakSelf 為什麼不管用

破局點在於「self 被強引用」。最直覺的想法是換成弱引用:

__weak typeof(self) weakSelf = self;
_timer = [NSTimer scheduledTimerWithTimeInterval:3.0f
                                         target:weakSelf
                                       selector:@selector(timerFire:)
                                       userInfo:nil
                                        repeats:YES];

遺憾的是這麼寫幾乎沒有任何作用。此處 `__weak` 與 `__strong` 的唯一差別是:如果在這兩行代碼執行期間 self 恰好被釋放,那麼 timer 的 target 會變成 nil。強引用閉環本身並沒有被打破。

五、方案二:引入一個「代理人」target

既然無法用 `__weak` 把 self 從閉環中剝離出來,那就乾脆造一個假的 target 頂上去。這個中間層只做一件事:替真正的業務對象接下 timer 的強引用。

@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

然後封裝一個同名的方法,在內部完成偷樑換柱:

+ (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;
}

再跑一次,洩露消失,dealloc 正常執行。

六、方案三:再包一層 block 語法

如果能用 block 寫定時器的回調邏輯,可讀性會更好一些:

+ (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];
    if (block) {
        block(info);
    }
}

調用起來就清爽多了:

- (IBAction)fireButtonPressed:(id)sender {
    _timer = [HWWeakTimer scheduledTimerWithTimeInterval:3.0f
                                                  block:^(id userInfo) {
        NSLog(@"%@", userInfo);
    }
                                               userInfo:@"Fire"
                                                repeats:YES];
    [_timer fire];
}

七、小結

NSTimer 的問題本質上是「非投放即釋放」的引用模型與「按需停止」需求之間的衝突。理解 Runloop 與 target 的雙重強引用,是排查這類洩露的前提;而中間層代理則是目前最通用、侵入最小的解法。上述代碼已簡單封裝為 HWWeakTimer,歡迎取用。

參考資料

  • Apple 官方 NSTimer 類參考

  • How to stop/invalidate NSTimer

  • Weak Reference to NSTimer Target To Prevent Retain Cycle

  • performSelector may cause a leak because its selector is unknown

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved