首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS NSTimer 非 scheduled 模式需手動加入 RunLoop 才能觸發

     編輯:程式設計綜合問答

用 [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,不會觸發

修正方案一:手動加入 RunLoop

NSTimer *timer = [NSTimer timerWithTimeInterval:0.2 target:self selector:@selector(removeOverlay) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
// 或 NSRunLoopCommonModes 兼容滾動等模式

修正方案二:使用 scheduled 工廠方法(推薦)

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(removeOverlay) userInfo:nil repeats:NO];
// 自動加入當前 RunLoop 的 defaultMode

關鍵區別

方法自動加入 RunLoop適用場景
timerWithTimeInterval:否需精確控制模式/時間的高級用法
scheduledTimerWithTimeInterval:是 (defaultMode)絕大多數定時任務

記憶體管理提醒

  • Target 會被 Timer 強引用,repeats:YES 時需在 dealloc 或適當時機 [timer invalidate],否則循環引用洩漏。
  • ARC 環境下屬性聲明 @property (nonatomic, strong) NSTimer *timer; 便於管理。

選對創建方式,Timer 準時觸發不再愁。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved