Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

37 题 block 循环引用问题 #50

Open
maquannene opened this issue Jul 8, 2016 · 5 comments
Open

37 题 block 循环引用问题 #50

maquannene opened this issue Jul 8, 2016 · 5 comments
Labels

Comments

@maquannene
Copy link

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

@HppZ
Copy link

HppZ commented Jul 19, 2016

__weak在mrc下可用

@HaiTeng-Wang
Copy link

@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下会有野指针?是吗?请好好看看我发的文档链接。也可自行测试。

@maquannene
Copy link
Author

maquannene commented May 16, 2018

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.

@songgeb
Copy link

songgeb commented Jul 19, 2018

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

@ChenYilong
Copy link
Owner

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

@ChenYilong ChenYilong added the Q-A label Jun 2, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants