NSTimer 常用的方法有三個
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(nullable id)ui repeats:(BOOL)rep;
scheduledTimerWithTimeInterval
是創建一個定時器,并加入到當前運行循環[NSRunLoop currentRunLoop]
中,而其他兩個只是創建定時器,并未添加到當前運行循環中,所以如果是其他兩種方式創建的定時器則需要手動添加到currentRunLoop
中,示例代碼如下:
NSTimer *timer1 = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(doSomeThing1) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer1 forMode:NSDefaultRunLoopMode];
NSTimer *timer2 = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:5] interval:3 target:self selector:@selector(doSomeThing2) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer2 forMode:NSDefaultRunLoopMode];
關于fire
方法并不是啟動一個定時器,只是提前觸發而已,詳情可查看蘋果文檔
fire:
You can use this method to fire a repeating timer without interrupting its regular firing schedule. If the timer is non-repeating, it is automatically invalidated after firing, even if its scheduled fire date has not arrived.
定時器如果不再使用的話,需要手動釋放,直接調用invalidate
即可,千萬不要放在dealloc里面調用invalidate,原因我就不說了,不懂可以google
invalidate:
This method is the only way to remove a timer from an NSRunLoop object. The NSRunLoop object removes its strong reference to the timer, either just before the invalidate method returns or at some later point.If it was configured with target and user info objects, the receiver removes its strong references to those objects as well.