最新 GCD 定时器 比NSTimer更准时的定时器
程序员文章站
2022-03-20 23:01:10
#import "ViewController.h"@interface ViewController ()@property (nonatomic, strong) dispatch_source_t timer;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; dispatch_queue_t queue = dispatch_get_main_queue();// d....
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) dispatch_source_t timer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_queue_t queue = dispatch_get_main_queue();
// dispatch_queue_t queue = dispatch_queue_create("timer", DISPATCH_QUEUE_SERIAL); // 主队列 串行队列都可以 主线程 子线程都可以
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
// 需要强引用
self.timer = timer;
// 2秒后开始 间隔1秒
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 2.0 * NSEC_PER_SEC, 1.0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
NSLog(@"===");
});
// 开始计时
dispatch_resume(timer);
// dispatch_source_cancel(timer) // 取消计时器
}
本文地址:https://blog.csdn.net/weixin_41963895/article/details/110580656