OGeek|极客世界-中国程序员成长平台

标题: ios - block 如何处理 __weak 引用 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 10:55
标题: ios - block 如何处理 __weak 引用

从关于打破 block 内保留循环的大量问题中,我的问题如下:

该 block 实际上如何处理其中的 __weak 引用?

我知道这一点(取自 here):

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

那么它是如何处理 __weak 资格所有权的呢?理论上因为它是 __weak 它不会保留它?会保留对它的引用吗?



Best Answer-推荐答案


正确,弱引用不会被保留。它完全按照您的预期工作。一旦对象被释放,它们就会被设置为 nil

虽然这通常很好(您不希望仅仅因为 block 的存在而保留它),但有时它可能会出现问题。通常,您希望确保一旦 block 被执行,它会在该 block 的执行期间保留(但不是在 block 执行之前)。为此,您可以使用 weakSelf/strongSelf 模式:

__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).
    }
};

这样,您不会有保留周期,但您不必担心如果您只使用 weakSelf 会导致异常或其他问题。

Use Lifetime Qualifiers to Avoid Strong Reference Cycles 中的“非平凡循环”讨论中说明了这种模式。在 David 引用的过渡到 ARC 发行说明中。

关于ios - block 如何处理 __weak 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16470324/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4