标签:
1 // 循环5次 2 for (int i =0; i < 5; i++ ) { 3 4 NSLog(@"let‘s go %d",i); 5 // 设置2秒后执行block 6 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 7 NSLog(@"This is my %d number!",i); 8 }); 9 }
1 2016-01-03 23:55:49.109 dispatchAfterDeep[1095:60579] let‘s go 0 2 2016-01-03 23:55:49.110 dispatchAfterDeep[1095:60579] let‘s go 1 3 2016-01-03 23:55:49.111 dispatchAfterDeep[1095:60579] let‘s go 2 4 2016-01-03 23:55:49.111 dispatchAfterDeep[1095:60579] let‘s go 3 5 2016-01-03 23:55:49.111 dispatchAfterDeep[1095:60579] let‘s go 4 6 2016-01-03 23:55:51.111 dispatchAfterDeep[1095:60579] This is my 0 number! 7 2016-01-03 23:55:51.300 dispatchAfterDeep[1095:60579] This is my 1 number! 8 2016-01-03 23:55:51.301 dispatchAfterDeep[1095:60579] This is my 2 number! 9 2016-01-03 23:55:51.301 dispatchAfterDeep[1095:60579] This is my 3 number! 10 2016-01-03 23:55:51.301 dispatchAfterDeep[1095:60579] This is my 4 number!
Declaration void dispatch_after( dispatch_time_t when, dispatch_queue_t queue, dispatch_block_t block); Parameters when The temporal milestone returned by dispatch_time or dispatch_walltime. queue The queue on which to submit the block. The queue is retained by the system until the block has run to completion. This parameter cannot be NULL. block The block to submit. This function performs a Block_copy and Block_release on behalf of the caller. This parameter cannot be NULL. Discussion This function waits until the specified time and then asynchronously adds block to the specified queue.
官方文档描述很简洁,翻译过来就是:这个函数等到特定的时间,然后异步添加block到指定的队列中;在示例程序1里面,指定的队列是主队列,也就是当进入循环的时候,会先执行打印了lets go语句,然后异步执行dispatch_after函数,由于内部使用变量来计时,所以“定时器”是设置在了主线程上,等待2秒然后开子线程将Block加入到主队列中,最后主队列按顺序执行Block,但是这样正确吗?
1 delay (2){ 2 3 dispatch_async(DISPATCH_QUEUE_SERIAL, ^{ 4 5 (add block into main queue); 6 7 }); 8 }
标签:
原文地址:http://www.cnblogs.com/Voodoodong/p/5097534.html