简体   繁体   中英

How blocks handles __weak references

From a huge number of questions about breaking retain cycles inside blocks, my question is the following:

How does the block actually handles __weak references inside of it?

I am aware of this (taken from here ):

Blocks will retain any NSObject that they use from their enclosing scope when they are copied.

So how does it takes care of the __weak qualification ownership? In theory since it is __weak it won't retain it? Will just keep a reference to it?

Correct, the weak references will not be retained. It works precisely as you would expect. They are set to nil once the object is deallocated.

While this is generally good (you don't want it to be retained by the mere existence of the block), sometimes it can be problematic. Often you want to make sure that once the block beings executing, it's retained for the duration of the execution of that block (but not prior to the execution of the block). For that, you can use the weakSelf / strongSelf pattern:

__weak MyClass *weakSelf = self;

self.block = ^{
    MyClass *strongSelf = weakSelf;

    if (strongSelf) {
        // ok do you can now do a bunch of stuff, using strongSelf
        // confident that you won't lose it in the middle of the block,
        // but also not causing a strong reference cycle (a.k.a. retain
        // cycle).
    }
};

That way, you won't have retain cycle, but you don't have to worry about it getting exceptions or other problems that can result if you just used weakSelf alone.

This pattern is illustrated in "non-trivial cycles" discussion in the Use Lifetime Qualifiers to Avoid Strong Reference Cycles in the Transitioning to ARC Release Notes that David referenced.

弱引用被弱捕获,因此指向它们的对象不一定在该块的生存期内保持活动状态。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM