iOSInterviewQuestions icon indicating copy to clipboard operation
iOSInterviewQuestions copied to clipboard

37 题 block 循环引用问题

Open maquannene opened this issue 8 years ago • 5 comments

ARC 下 __weak 可避免循环引用,__block 不行。 __block 仅在 MRC 下可解决循环引用的问题,但是会有野指针的问题。

maquannene avatar Jul 08 '16 06:07 maquannene

__weak在mrc下可用

HppZ avatar Jul 19 '16 11:07 HppZ

@HppZ 请注意:__weak是iOS4.2的之后ARC产物。你可以在MRC是使用__weak测试下。会爆警告:'__weak' only applies to Objective-C object or block pointer types; type here is 'int'。而block块内操作的变量会爆红:Variable is not assignable (missing __block type specifier)。

@maquannene __weak修饰符的语义:指定一个引用,该引用不会使引用的对象保持活着状态。 当没有强引用时,弱引用设置为零,指针置空nil。官方文档:https://developer.apple.com/library/content/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011226-CH1-SW4

对于楼主的issue第一句话“ARC 下 __weak 可避免循环引用,__block 不行”认同。 第二句话“__block 仅在 MRC 下可解决循环引用的问题,但是会有野指针的问题。”不认同。 __block在MRC下会有野指针?是吗?请好好看看我发的文档链接。也可自行测试。

HaiTeng-Wang avatar Apr 28 '18 03:04 HaiTeng-Wang

It waste my 5 minutes to prove my hesitation.

In order to prevent I get this rude question to wast my time again, i paste official docs which @HaiTeng-Wang provided:

In manual reference counting mode, __block id x; has the effect of not retaining x. In ARC mode, __block id x; defaults to retaining x (just like all other values). To get the manual reference counting mode behavior under ARC, you could use __unsafe_unretained __block id x;. As the name __unsafe_unretained implies, however, having a non-retained variable is dangerous (because it can dangle) and is therefore discouraged. Two better options are to either use __weak (if you don’t need to support iOS 4 or OS X v10.6), or set the __block value to nil to break the retain cycle.

maquannene avatar May 16 '18 15:05 maquannene

@ChenYilong 既然ARC下__block无法避免循环引用,那为什么不修正答案呢?补充一点,OC高级编程一书中有说__block可以避免循环引用,但前提是要及时的将__block变量置为nii.

songgeb avatar Jul 19 '18 11:07 songgeb

已更正,并在文中附带了该 issue 讨论链接

ChenYilong avatar Jun 02 '20 04:06 ChenYilong