dispatch_after 造成对象延迟释放

最近做需求发现,引入dispatch_after后,在dispatch_after执行期间会引起对象延迟释放

官网对dispatch_after描述如下:

该函数等待指定的时间,然后异步地将块添加到指定的队列。

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.
提交Block的时间节点
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.
提交的块。此函数代表调用方执行Block_copy和Block_release。此参数不能为空。

Discussion
This function waits until the specified time and then asynchronously adds block to the specified queue.
该函数等待指定的时间,然后异步地将块添加到指定的队列。

原文:示例如下

   // 循环5次
     for (int i =0; i < 5; i++ ) {
         
         NSLog(@"let‘s go %d",i);
         // 设置2秒后执行block
         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             NSLog(@"This is my %d number!",i);
         });
     }
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!

在示例程序1里面,指定的队列是主队列,也就是当进入循环的时候,会先执行打印了lets go语句,然后异步执行dispatch_after函数,由于内部使用变量来计时,所以“定时器”是设置在了主线程上,等待2秒然后开子线程将Block加入到主队列中,最后主队列按顺序执行Block,但是这样正确吗?

把示例程序的循环次数加到1000次就会发现,Block依然是按顺序执行,但是异步添加Block到主队列肯定不会按顺序添加,主队列又是顺序执行,那么一定会有顺序错误的打印出现,可是继续增加到10000次还是按顺序执行,那么这里dispatch_after函数可能是将添加Block的操作放入一个串行队列,然后在子线程上执行队列,将BLock添加到主队列中,最后主队列执行Block操作。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容