最近做需求發(fā)現(xiàn),引入dispatch_after后,在dispatch_after執(zhí)行期間會(huì)引起對(duì)象延遲釋放
官網(wǎng)對(duì)dispatch_after描述如下:
該函數(shù)等待指定的時(shí)間,然后異步地將塊添加到指定的隊(duì)列。
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的時(shí)間節(jié)點(diǎn)
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.
要在其上提交塊的隊(duì)列。隊(duì)列被系統(tǒng)保留,直到塊運(yùn)行完成。此參數(shù)不能為空。`
block
The block to submit. This function performs a Block_copy and Block_release on behalf of the caller. This parameter cannot be NULL.
提交的塊。此函數(shù)代表調(diào)用方執(zhí)行Block_copy和Block_release。此參數(shù)不能為空。
Discussion
This function waits until the specified time and then asynchronously adds block to the specified queue.
該函數(shù)等待指定的時(shí)間,然后異步地將塊添加到指定的隊(duì)列。
原文:示例如下
// 循環(huán)5次
for (int i =0; i < 5; i++ ) {
NSLog(@"let‘s go %d",i);
// 設(shè)置2秒后執(zhí)行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里面,指定的隊(duì)列是主隊(duì)列,也就是當(dāng)進(jìn)入循環(huán)的時(shí)候,會(huì)先執(zhí)行打印了lets go語(yǔ)句,然后異步執(zhí)行dispatch_after函數(shù),由于內(nèi)部使用變量來(lái)計(jì)時(shí),所以“定時(shí)器”是設(shè)置在了主線程上,等待2秒然后開(kāi)子線程將Block加入到主隊(duì)列中,最后主隊(duì)列按順序執(zhí)行Block,但是這樣正確嗎?
把示例程序的循環(huán)次數(shù)加到1000次就會(huì)發(fā)現(xiàn),Block依然是按順序執(zhí)行,但是異步添加Block到主隊(duì)列肯定不會(huì)按順序添加,主隊(duì)列又是順序執(zhí)行,那么一定會(huì)有順序錯(cuò)誤的打印出現(xiàn),可是繼續(xù)增加到10000次還是按順序執(zhí)行,那么這里dispatch_after函數(shù)可能是將添加Block的操作放入一個(gè)串行隊(duì)列,然后在子線程上執(zhí)行隊(duì)列,將BLock添加到主隊(duì)列中,最后主隊(duì)列執(zhí)行Block操作。