前言
相信一说到定时器, 我们使用最多的就是NSTimer 和 GCD 了, 还有另外一个高级的定时器 CADisplayLink;,下面将给大家详细介绍关于iOS定时器使用的相关内容,话不多说了,来一起看看详细的介绍吧。
一. NSTimer
NSTimer的初始化方法有以下几种:
会自动启动, 并加入 MainRunloop 的 NSDefaultRunLoopMode 中,
注意: 这里的自动启动, 并不是马上就会启动, 而是会延迟大概一个interval的时间:
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block
参数:
internal : 时间间隔, 多久调用一次 repeats: 是否重复调用 block: 需要重复做的事情使用:
[NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
static NSInteger num = 0;
NSLog(@"%ld", (long)num);
num++;
if (num > 4) {
[timer invalidate];
NSLog(@"end");
}
}];
NSLog(@"start");
这时, 控制台的输出:
2016-12-29 16:29:53.901 定时器[11673:278678] start
2016-12-29 16:29:54.919 定时器[11673:278678] 0
2016-12-29 16:29:55.965 定时器[11673:278678] 1
2016-12-29 16:29:56.901 定时器[11673:278678] 2
2016-12-29 16:29:57.974 定时器[11673:278678] 3
2016-12-29 16:29:58.958 定时器[11673:278678] 4
2016-12-29 16:29:58.959 定时器[11673:278678] end
可以看出, 这里的internal设置为1s, 大概延迟了1s才开始执行block里的内容;
这里的停止定时器, 我直接在block里进行的, 如果使用一个全局变量来再其他地方手动停止定时器,需要这样进行:
[self.timer invalidate];
self.timer = nil;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo
参数:
ti: 重复执行时间间隔 invocation: NSInvocation实例, 其用法见NSInvocation的基本用法 yesOrNo: 是否重复执行示例:
// NSInvocation形式
- (void)timer2 {
NSMethodSignature *method = [ViewController instanceMethodSignatureForSelector:@selector(invocationTimeRun:)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:method];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 invocation:invocation repeats:YES];
// 设置方法调用者
invocation.target = self;
// 这里的SEL需要和NSMethodSignature中的一致
invocation.selector = @selector(invocationTimeRun:);
// 设置参数
// //这里的Index要从2开始,以为0跟1已经被占据了,分别是self(target),selector(_cmd)
// 如果有多个参数, 可依次设置3 4 5 ...
[invocation setArgument:&timer atIndex:2];
[invocation invoke];
NSLog(@"start");
}
- (void)invocationTimeRun:(NSTimer *)timer {
static NSInteger num = 0;
NSLog(@"%ld---%@", (long)num, timer);
num++;
if (num > 4) {
[timer invalidate];
}
}










