GCD之dispatch_source定时器Timer
2017-06-02 本文已影响62人
朽木自雕也
__block NSIntager i =0;
创建定时器源
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,dispatch_get_main_queue());
从现在开始计算0秒后开始
dispatch_time_t start = dispatch_time(FISPATCH_TIME_NOW,0);
设置定时器循环的时间为3秒
dispatch_source_set_time(timer,start,3.0*NSEC_PER_SEC,0);
平均每三秒把block放入主线程执行一遍
dispatch_source_set_event_handler(timer,^{
i++;
NSLog(@"%ld",i);
if(i>=5){
dispatch_cancel(time);
}
});