作用:用来定时重复执行某件事件
注意:计时器需要放入到runloop中才能有用
NSTimer常用方法
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block
//以上2个方法创建时会默认放入当前runloop中,默认runloop模式是NSDefaultRunLoop。创建时即可使用
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block
//以上2个方法创建后需要手动放入runloop中,并指定runloop模式后才可用。如
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
- (void)fire;//重新开始计时器
- (void)invalidate;//销毁计时器
如
[timer invalidate];
timer=nil;
属性:
valid--是否可用
userInfo--携带的信息
fireDate--设置开启时间
用法:
timer.fireDate = [NSDate distantFuture];//在未来某个时间开启,即暂停
timer.fireDate = [NSDate distantPast];//在过去的某个时间开始,即启动
举例:
//直接创建即可使用
NSTimer * timer1 = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doSomething:) userInfo:@"hello world" repeats:YES];
//创建后需要手动加入到runloop中
NSTimer * timer2 = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(doSomething:) userInfo:@"hello world" repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer2 forMode:NSDefaultRunLoopMode];
//销毁
[timer invalidate];
timer = nil;