- (void)viewDidLoad {
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(actionTimer:)
userInfo:nil
repeats:YES];
}
- (void)actionTimer:(NSTimer *)timer {
}
NSTimer 預設跑在 default mode,幾乎涵蓋所有輸入源(NSConnection 除外),也就是 NSDefaultRunLoopMode。上面的寫法會讓 actionTimer: 每秒被呼叫一次,用起来確實非常直覺。
所謂「主界面被滑動」,指的是頁面上有 UITableView 或 UIScrollView,而使用者正在拖動它。這時候 NSTimer 就停止觸發了。
寫個 demo 驗證:在一個含 UITableView 的 UIViewController 上啟動計時器,每秒把數字加一並更新到 UILabel。
- (void)viewDidLoad {
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(actionTimer:)
userInfo:nil
repeats:YES];
}
- (void)actionTimer:(NSTimer *)timer {
self.number++;
self.label.text = [NSString stringWithFormat:@"%d", self.number];
NSLog(@"%d", self.number);
}
結果如預期:當使用者拖動 UITableView 時,RunLoop 進入 UITrackingRunLoopMode,NSTimer 無法 fire,UILabel 上的數字也就停在原地。

把 timer 明確加入 UITrackingRunLoopMode 或 NSRunLoopCommonModes:
[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
或者:
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
NSRunLoopCommonModes 是一個模式集合,把事件源綁到這個集合,就等於綁進集合內的每一種模式,因此滑動時也不會中斷。

直覺上會這樣寫:
@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。但當你從這個頁面跳走,控制台卻還在源源不絕地輸出——計時器根本沒停。
於是在 dealloc 裡補上 invalidate:
- (void)dealloc {
[_timer invalidate];
NSLog(@"%@ dealloc", NSStringFromClass([self class]));
}
再跑一次,還是停不下來。原因是 NSTimer 被加入 RunLoop 時會被強引用:
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(也就是 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 強引用 self,導致 self 永遠無法釋放,dealloc 自然永遠不會被呼叫。於是只能再加一顆 invalidate 按鈕:
- (IBAction)invalidateButtonPressed:(id)sender {
[_timer 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 在哪條 thread 建立,就必須在同一條 thread 停止,否則資源無法被正確回收。
如果需求是「一直輸出,直到頁面銷毀才停止」,你會發現邏輯繞成一圈:
實務上常見的解法有幾種:用 weak proxy 中轉訊息、改用 GCD Timer、或在 iOS 10 以後直接使用 block 版本的 scheduledTimerWithTimeInterval:repeats:block:,都能避開這個循環引用。