您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

NSTimer 使用進階:洩漏、生命週期與 Weak Timer

編輯:iOS 開發基礎

NSTimer 是 iOS 開發中常見的定時工具,但若使用不當,容易造成內存洩漏、生命週期錯誤甚至崩潰。本文總結使用 NSTimer 時需要重點關注的問題。

NSTimer 循環引用

為什麼 NSTimer 容易洩漏

當使用 scheduledTimerWithTimeInterval 創建重複定時器時,RunLoop 會持有 timer,timer 又強引用 target。如果 target 是當前對象,就會形成循環引用,導致對象無法釋放。

self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                              target:self
                                            selector:@selector(update)
                                            userInfo:nil
                                             repeats:YES];

因此,必須在合適的時機調用 invalidate。若把 invalidate 寫在 dealloc 中,通常沒有效果,因為 timer 未停止前,self 不會被釋放,dealloc 也不會被調用。

正確的生命週期管理

應根據業務場景啟動與停止 timer。例如頁面可見時啟動,頁面不可見時停止:

- (void)viewWillAppear {
    [super viewWillAppear];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(update)
                                                userInfo:nil
                                                 repeats:YES];
}

- (void)viewDidDisappear {
    [super viewDidDisappear];
    [self.timer invalidate];
}

常見錯誤特徵

  • 在 dealloc 中停止 timer,通常說明作者對引用關係理解不足。
  • 創建 timer 後不保存引用,後續無法停止。
  • 在 viewDidAppear 中創建 timer,但沒有成對的停止時機,容易重複創建。

停止 timer 引發的野指針

調用 invalidate 後,timer 會釋放 target。如果 target 只被 timer 持有,停止後對象可能被立即釋放。此後再通過 self 訪問成員,就可能發生野指針崩潰。

- (void)onEnterBackground:(id)sender {
    [self.timer invalidate];
    [self.view stopAnimation];
}

臨時方案是使用 weak 引用,但根本解決方式仍是排查為何 timer 直到此時才停止,以及是否有其他對象仍應持有 self。

Perform Delay 的注意事項

performSelector:withObject:afterDelay: 本質上也是一次性 timer,因此同樣需要關注取消與生命週期。必要時可調用 cancelPreviousPerformRequestsWithTarget:selector:object: 取消之前排隊的請求。

RunLoop Mode 的影響

NSTimer 添加到當前 RunLoop 的某個 mode。若 RunLoop 暫時不在該 mode,例如列表跟手滾動時主線程處於 tracking mode,timer 回調可能被延遲。若希望滾動時也觸發,可將 timer 添加到 common modes。

Weak Timer

為了避免 timer 強引用 target,可以使用 Weak Timer。常見方案是在 timer 與 target 之間增加一層 proxy,由 proxy 弱引用真實 target,並轉發消息。

Weak Timer 代理

也可以基於 GCD timer 自行封裝一個弱引用版本,在定時器中只持有 weak target。

總結

NSTimer 本身並不複雜,但涉及 RunLoop、引用循環與生命週期。開發時應始終關注三件事:誰持有 timer、timer 持有誰、以及 timer 在哪裡停止。把這些問題想清楚,才能避免洩漏與崩潰。

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