NSTimer 是 iOS 中常見的定時器,可用來在指定時間後執行方法,或重複執行。建立方式有兩種:timerWithTimeInterval 與 scheduledTimerWithTimeInterval。
使用 timerWithTimeInterval 建立後,需要手動加入 run loop,例如 addTimer:forMode:。使用 scheduledTimerWithTimeInterval 則會自動以預設模式加入目前的 run loop。
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];
若使用非 scheduled 方式:
NSTimer *myTimer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO]; [[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSDefaultRunLoopMode];
定時器建立並加入 run loop 後,會在指定的 timeInterval 秒後觸發。若要立即觸發,可呼叫 fire。對於重複執行的定時器,fire 不會中斷原本的排程;對於非重複定時器,觸發後會自動失效。
停止定時器可呼叫 invalidate。這也是把計時器從 run loop 中移除的主要方法。
NSTimer 並非絕對精準,通常會受到系統負載與 run loop 阻塞影響。若中間耗時過長,可能錯過觸發時間。因此它適合一般 UI 計時,不適合要求極高精度的場景。