GCD定时器

GCD定时器

by 伍雪颖

+ (GCDTimer *)repeatingTimer:(NSTimeInterval)seconds
                                      block:(void (^)(void))block {
  NSParameterAssert(seconds);
  NSParameterAssert(block);

  GCDTimer *timer = [[self alloc] init];
  timer.block = block;
  timer.source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,
                                        0, 0,
                                        dispatch_get_main_queue());
  uint64_t nsec = (uint64_t)(seconds * NSEC_PER_SEC);
  dispatch_source_set_timer(timer.source,
                            dispatch_time(DISPATCH_TIME_NOW, nsec),
                            nsec, 0);
  dispatch_source_set_event_handler(timer.source, block);
  dispatch_resume(timer.source);
  return timer;
}

- (void)invalidate {
  if (self.source) {
    dispatch_source_cancel(self.source);
    self.source = nil;
  }
  self.block = nil;
}

__block int n=0;
    self.timer = [GCDTimer repeatingTimer:1 block:^{
        n++;
        NSLog(@"Hello");
        if (n == 3) {
            [self.timer invalidate];
        }
    }];
使用简单方便.

posted on 2016-02-17 14:30  gcczhongduan  阅读(163)  评论(0编辑  收藏  举报