NSTimer 常用的方法有三個(gè)
+ (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
是創(chuàng)建一個(gè)定時(shí)器驶鹉,并加入到當(dāng)前運(yùn)行循環(huán)[NSRunLoop currentRunLoop]
中橙凳,而其他兩個(gè)只是創(chuàng)建定時(shí)器褐隆,并未添加到當(dāng)前運(yùn)行循環(huán)中,所以如果是其他兩種方式創(chuàng)建的定時(shí)器則需要手動(dòng)添加到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];
關(guān)于fire
方法并不是啟動(dòng)一個(gè)定時(shí)器,只是提前觸發(fā)而已袜炕,詳情可查看蘋果文檔
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.
定時(shí)器如果不再使用的話,需要手動(dòng)釋放初家,直接調(diào)用invalidate
即可偎窘,千萬(wàn)不要放在dealloc里面調(diào)用invalidate,原因我就不說(shuō)了溜在,不懂可以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.