NSTimer不准,scheduleTimer放在runloop里面,受runloop模式影响会不准
// [NSTimer scheduledTimerWithTimeInterval:<#(NSTimeInterval)#> target:<#(nonnull id)#> selector:<#(nonnull SEL)#> userInfo:<#(nullable id)#> repeats:<#(BOOL)#>];
所以创建GCD定时器
//dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, <#dispatchQueue#>);
//dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, <#intervalInSeconds#> * NSEC_PER_SEC, <#leewayInSeconds#> * NSEC_PER_SEC);
//dispatch_source_set_event_handler(timer, ^{
// <#code to be executed when timer fires#>
//});
// [NSTimer scheduledTimerWithTimeInterval:<#(NSTimeInterval)#> target:<#(nonnull id)#> selector:<#(nonnull SEL)#> userInfo:<#(nullable id)#> repeats:<#(BOOL)#>];
所以创建GCD定时器
//dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, <#dispatchQueue#>);
//dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, <#intervalInSeconds#> * NSEC_PER_SEC, <#leewayInSeconds#> * NSEC_PER_SEC);
//dispatch_source_set_event_handler(timer, ^{
// <#code to be executed when timer fires#>
//});
//dispatch_resume(timer);
看下面实例:
#import "ViewController.h"
@interface ViewController ()
/** 定时器(这里不用带*,因为dispatch_source_t就是个类,内部包含了) */
@property (nonatomic, strong) dispatch_source_t timer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//获得队列
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(0, 0);
//创建一个gcd定时器 (dispatch_source_t timer:dispatch_source_t本质还是个OC对象,是个局部变量,需要强引用,不然下面使用无效)
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatchQueue);
//OC对象%@可以打印
NSLog(@"%@", self.timer);
//设置定时器的各种属性(几时开始,每隔多长时间执行一次)
//GCD时间参数,一般是纳秒 NSEC_PER_SEC 纳秒单位等于一秒;DISPATCH_TIME_NOW当前时间
dispatch_time_t start = DISPATCH_TIME_NOW;
uint64_t interval = (uint64_t)(2.0 *NSEC_PER_SEC);
dispatch_source_set_timer(self.timer, start, interval, 0);
dispatch_source_set_event_handler(self.timer, ^{
NSLog(@"--------%@",[NSThread currentThread]);
});
//启动定时器
dispatch_resume(self.timer);
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"----touchesBegan点击取消定时器!");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//取消定时器
dispatch_cancel(self.timer);
self.timer = nil;
NSLog(@"%@",self.timer);
});
}
@end
实例可直接使用,可以封装成timer类使用,懂了的请点赞哦!!!