dispatch_after
- dispatch_after
dispatch_after
dispatch_after函数并不是延迟对应时间后立即执行block块中的操作,而是将任务追加到对应队列中,考虑到队列阻塞等情况,所以这个任务从加入队列到真正执行的时间是不准确的。
dispatch_after(dispatch_time_t when,dispatch_queue_t queue,dispatch_block_t block);
一些例子:
//永远不执行block中代码(这个基本不用)
dispatch_after(DISPATCH_TIME_FOREVER, dispatch_get_main_queue(), ^{NSLog(@"1%@",[NSThread currentThread]);
});//现在就在主线程中执行block中的代码(基本不用)
dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), ^{NSLog(@"2%@",[NSThread currentThread]);
});//延迟2秒后再主线程执行block中的代码
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{NSLog(@"3%@",[NSThread currentThread]);
});//延迟2秒后在开一个新的子线程执行block中代码
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_global_queue(0, DISPATCH_QUEUE_PRIORITY_DEFAULT), ^{NSLog(@"4%@",[NSThread currentThread]);
});