用 [NSTimer timerWithTimeInterval:...] 創建的 Timer 若不加入 RunLoop,不會觸發。必須手動調用 [[NSRunLoop currentRunLoop] addTimer:forMode:],或改用 scheduledTimerWithTimeInterval: 自動加入當前 RunLoop。
NSTimer *timer = [NSTimer timerWithTimeInterval:0.2 target:self selector:@selector(removeOverlay) userInfo:nil repeats:NO];
// ❌ 未加入 RunLoop,不會觸發
NSTimer *timer = [NSTimer timerWithTimeInterval:0.2 target:self selector:@selector(removeOverlay) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
// 或 NSRunLoopCommonModes 兼容滾動等模式
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(removeOverlay) userInfo:nil repeats:NO];
// 自動加入當前 RunLoop 的 defaultMode
| 方法 | 自動加入 RunLoop | 適用場景 |
|---|---|---|
timerWithTimeInterval: | 否 | 需精確控制模式/時間的高級用法 |
scheduledTimerWithTimeInterval: | 是 (defaultMode) | 絕大多數定時任務 |
repeats:YES 時需在 dealloc 或適當時機 [timer invalidate],否則循環引用洩漏。@property (nonatomic, strong) NSTimer *timer; 便於管理。選對創建方式,Timer 準時觸發不再愁。