iOS 定时器

开始bash

-(void)startTimer{
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0.1 * NSEC_PER_SEC);
    @weakify(self);
    dispatch_source_set_event_handler(self.timer, ^{
        @strongify(self);
        [self countTime];
    });
    dispatch_resume(self.timer);
}
复制代码

计时ui

- (void)countTime {
    countTime ++;
    NSLog(@"%ld",(long)countTime);
    if (self->countTime >= self->limitTime) {
            [self stopTimer];
        }
}
复制代码

中止spa

- (void)stopTimer{
    if (_timer) {
        if (dispatch_testcancel(_timer) != 0) {
            dispatch_cancel(_timer);
        }
        _timer = nil;
    }
}
复制代码
相关文章
相关标签/搜索