有三种方法来创建一个定时器
1.使用scheduledTimerWithTimeInterval
类方法创建计时器和进度上当前运行循环在默认模式(NSDefaultRunLoopMode)
2.使用timerWithTimerInterval
类方法创建计时器对象没有调度运行循环(RunLoop)
在创建它,必须手动添加计时器运行循环,通过调用adddTimer:forMode:方法相应的NSRunLoop对象
3.使用initWithFireDate
在创建它,必须手动添加计时器运行循环,通过使用addTimer:forMode:方法相应的NSRunLoop对象
1.
- (void)execute { NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; [[NSRunLoop currentRunLoop] run]; }
2.
- (void)execute { [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:YES]; //为什么在主线程不需要这句run,那是因为主线程有RunLoop而且已经启动 [[NSRunLoop currentRunLoop] run]; } 给人感觉还是使用timerWithTimerInterval这种方式好些,可控性强一些,而且可以不用因为主线程阻塞(如视频推拉流)而造成timer的事件卡顿. 例如这样一个跑马灯的效果: dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // self.LampTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(lampsStart:) userInfo:nil repeats:YES]; self.LampTimer = [NSTimer timerWithTimeInterval:0.618 target:self selector:@selector(lampsStart:) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:self.LampTimer forMode:NSRunLoopCommonModes]; [self.LampTimer fire]; [[NSRunLoop currentRunLoop] run]; }); 更多问题,欢迎加群讨论:qq群 :565191947