NSTimer
介绍
- NSTimer其实是将一个监听加入到系统的RunLoop中去,当系统runloop到如何timer条件的循环时,会调用timer一次,当timer执行完,也就是回调函数执行之后,timer会再一次的将自己加入到runloop中去继续监听。
- CFRunLoopTimerRef 和 NSTimer这两个类型是可以互换的, 当我们在传参数的时候,看到CFRunLoopTimerRef可以传NSTimer的参数,增加强制转化来避免编译器的警告信息
初始化
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(action) userInfo:nil repeats:NO];
NSTimer *tm = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:3.0 target:self selector:@selector(anctiontm) userInfo:nil repeats:YES];
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
基本函数运用
[timer fire];
[timer invalidate];
BOOL tmp = [timer isValid];
[timer setFireDate:[NSDate date]];
注意
注意:将计数器的repeats设置为YES的时候,self的引用计数会加1。因此可能会导致self(即viewController)不能release,所以,必须在viewWillAppear的时候,将计数器timer停止,否则可能会导致内存泄露。
[timer invalidate];
timer = nil;
[timer setFireDate:[NSDate distantFuture]];
[timer setFireDate:[NSDate distantPast]];