创建GCD定时器

2019-03-27  本文已影响0人  麻辣十三香小龙虾
/**
 创建一个定时器
 
 @param target 定时器持有者
 @param timeInterval 心跳时间
 @param handler stop=YES 销毁定时器
 */
void help_dispatch_timer(id target, double timeInterval, void (^handler)( BOOL * _Nonnull stop))
{
    __weak __typeof(target) weak_target  = target;
    __block BOOL stop = NO;
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, timeInterval * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (weak_target)  {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (handler) {
                    if (stop) {
                        long state = dispatch_source_testcancel(timer);
                        if (0==state) {
                            dispatch_source_cancel(timer);
                        }
                    }else{
                        handler(&stop);
                    }
                }else{
                    long state = dispatch_source_testcancel(timer);
                    if (0==state) {
                        dispatch_source_cancel(timer);
                    }
                }
            });
        } else {
            long state = dispatch_source_testcancel(timer);
            if (0==state) {
                dispatch_source_cancel(timer);
            }
        }
    });
    // 启动定时器
    dispatch_resume(timer);
}

举个栗子:

- (void)testDispatchTimer
{
    __weak typeof(self) self_weak_ = self;
    help_dispatch_timer(self, 2, ^(BOOL * _Nonnull stop) {
        self_weak_.label.text = [NSString stringWithFormat:@"%d",++count];
        if (6<=count) {
            *stop = YES;
        }
    });
}
上一篇 下一篇

猜你喜欢

热点阅读