+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo; + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
注意:userInfo 是 NSTimer 攜帶的使用者資訊。
若未使用 scheduled 方式初始化,需手動呼叫 addTimer:forMode: 將 timer 加入某個 run loop;而 scheduled 的初始化方法則會以預設 mode 直接加入目前的 run loop。
範例:
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(startFindApartment:) userInfo:nil repeats:YES]; // 或 NSTimer *myTimer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO]; [[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSDefaultRunLoopMode];
定時器建立後(若非 scheduled 則加入 run loop 後),會在初始化時指定的 timeInterval 秒後自動觸發。
NSTimer *timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(timeSchedule) userInfo:nil repeats:YES]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; [runLoop addTimer:timer forMode:NSDefaultRunLoopMode]; [timer fire]; // 可立即觸發
可使用 -(void)fire; 方法立即觸發定時器。
- (void)invalidate;
這是唯一能將計時器從 run loop 移除的方法。
在主執行緒(main thread)中使用定時器時,兩種初始化方法都能用;若是在子執行緒中使用,則只能使用方法一 timerWithTimeInterval:...,並且啟動時不能用 fire,只能讓 run loop 持續執行下去:
_timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(timeSchedule) userInfo:nil repeats:YES]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; [runLoop addTimer:_timer forMode:NSDefaultRunLoopMode]; while ([runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);