HR's Blog

Swimming 🏊 in the sea🌊of code!

0%

GCD Block循环引用问题

.

问题:GCD为什么不会导致循环引用

这个问题得分开回答,同步和异步线程

1.同步线程的情况

dispatch_sync苹果官方是这么写的

Unlike with dispatch_async, no retain is performed on the target queue. Because calls to this function are synchronous, it “borrows” the reference of the caller. Moreover, no Block_copy is performed on the block.
As a performance optimization, this function executes blocks on the current thread whenever possible, with one exception: Blocks submitted to the main dispatch queue always run on the main thread.
也就是说同步线程不会增加引用计数,是借用调用者的引用计数,而且也是同步执行,而且也不会把block拷贝,所以不会导致循环引用。

2. 异步线程的情况

dispatch_async苹果官方的描述是

The block to submit to the target dispatch queue. This function performs Block_copy and Block_release on behalf of callers. This parameter cannot be NULL.

也就是说会拷贝block,但是也会帮你调用release,所以也不会存在循环引用的问题。

References

GCD 捕获 self 是否会造成内存泄漏?
YYKit作者讨论