1.声明一个定时器变量
NSTimer *_timer;
2.启动一个定时器
- (void)startTimer
{
_timer = [[NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(onTimer) userInfo:nil repeats:NO] retain];
}
定时时间30秒,30秒后调用self的onTimer方法,执行定时操作,不重复
3.停止或中断定时器
- (void)stopTimer
{
if(_timer != nil){
[_timer invalidate]; //废弃定时器
[_timer release];
_timer = nil;
}
}
4.定时器调用的方法onTimer
- (void)onTimer
{
[self stopTimer];
//执行自定义逻辑
}
5.初始化的区别
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
推荐使用scheduled
timerWithTimeInterval初始化时,需要手动addTimer:forMode:,将timer添加到runloop中
而scheduled初始化时,已经使用了默认的mode并添加到了当前runloop中,不需要手动添加
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(onTimer:) userInfo:nil repeats:NO]; 等效于 NSTimer *timer2 = [NSTimertimerWithTimeInterval:30.0 target:selfselector:@selector(onTimer:) userInfo:nil repeats:NO]; [[NSRunLoopcurrentRunLoop] addTimer:timer2 forMode:NSDefaultRunLoopMode];
6. 立即触发某定时器
- (void)fire;
定时器默认在timeInterval后执行某动作,如果调用上面fire方法,则立即执行制定的动作,并使定时器无效
(重复执行的定时器,调用此方法也是立即执行指定动作,但不会中断原来执行计划)