12345678 表明1-8种建立方式macos
参数介绍:
interval: 时间间隔,单位:秒,若是<0,系统默认为0.1
target: 定时器绑定对象,通常都是self
selector: 须要调用的实例方法
userInfo: 传递相关信息
repeats: YES:循环 NO:执行一次就失效
block: 须要执行的代码块 做用等同于 selector里边的方法体
invocation: 须要执行的方法,具体使用方法能够本身baidu,如今这个已经不多用了。
fireDate: 触发的时间,通常都写[NSDate date],这样的话定时器会立马触发一次,而且以此时间为基准。若是没有此参数的方法,则都是以当前时间为基准,第一次触发时间是当前时间加上时间间隔interval
复制代码
#pragma mark - CreateTimer
- (void)createTimer{
NSInvocation *invocation = [[NSInvocation alloc] init];
//1
NSTimer *timer1 = [NSTimer timerWithTimeInterval:1 invocation:invocation repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer1 forMode:NSDefaultRunLoopMode];
//2
[NSTimer scheduledTimerWithTimeInterval:1 invocation:invocation repeats:YES];
//3
[NSTimer timerWithTimeInterval:1 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
//4
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
//5 API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0))
[NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
//定时器须要执行的方法
}];
//6 API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0))
[NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
//定时器须要执行的方法
}];
NSDate *date = [NSDate date];
//7 API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0))
NSTimer *timer7 = [[NSTimer alloc] initWithFireDate:date interval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
//定时器须要执行的方法
}];
[timer7 fire];
//8
NSTimer *timer8 = [[NSTimer alloc] initWithFireDate:date interval:1 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
//该方法表示定时器只会执行一次,无视repeats
[timer8 fire];
}
- (void)doSomething{
NSLog(@"do something");
}
复制代码
十二、3四、5六、78 是参数对应的关系
复制代码
timerWithTimeInterval
135bash
scheduledTimerWithTimeInterval
246oop
initWithFireDate
78post
一种须要手动加入runloop
1357八、另外一种就是自动加入runloop
246(弊端:runloop
只能是当前runloop
,模式是NSDefaultRunLoopMode
)spa
这里须要注意一个问题,子线程的runloop
是默认不开启的,在子线程建立timer
以后记得开启[[NSRunloop currentRunloop] run]
。线程