Skip to content

37 题 block 循环引用问题 #50

Open
@maquannene

Description

@maquannene

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

Activity

HppZ

HppZ commented on Jul 19, 2016

@HppZ

__weak在mrc下可用

HaiTeng-Wang

HaiTeng-Wang commented on Apr 28, 2018

@HaiTeng-Wang

@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

maquannene commented on May 16, 2018

@maquannene
Author

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

songgeb commented on Jul 19, 2018

@songgeb

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

ChenYilong

ChenYilong commented on Jun 2, 2020

@ChenYilong
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @ChenYilong@songgeb@maquannene@HppZ@HaiTeng-Wang

        Issue actions

          37 题 block 循环引用问题 · Issue #50 · ChenYilong/iOSInterviewQuestions