代码:
@interface ViewController () @property (nonatomic, strong) dispatch_source_t timer; @end @implementation ViewController - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { dispatch_queue_t dispatchQueue = dispatch_get_main_queue(); // dispatch_source_t本质是一个OC对象 dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatchQueue); dispatch_time_t start = DISPATCH_TIME_NOW; uint64_t interval = 1 * NSEC_PER_SEC; uint64_t leeway = 0 * NSEC_PER_SEC; dispatch_source_set_timer(timer, start, interval, leeway); dispatch_block_t _Nullable handler = ^void(void) { // code... }; dispatch_source_set_event_handler(timer, handler); dispatch_resume(timer); self.timer = timer; } @end