菜鸟教程小白 发表于 2022-12-12 10:55:01

ios - block 如何处理 __weak 引用


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

<p>该 block 实际上如何处理其中的 <code>__weak</code> 引用? </p>

<p>我知道这一点(取自 <a href="http://www.cocoawithlove.com/2009/10/how-blocks-are-implemented-and.html" rel="noreferrer noopener nofollow">here</a>):</p>

<blockquote>
<p>Blocks will retain any NSObject that they use from their enclosing
scope when they are copied.</p>
</blockquote>

<p>那么它是如何处理 <code>__weak</code> 资格所有权的呢?理论上因为它是 <code>__weak</code> 它不会保留它?会保留对它的引用吗?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>正确,弱引用不会被保留。它完全按照您的预期工作。一旦对象被释放,它们就会被设置为 <code>nil</code>。 </p>

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

<pre><code>__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&#39;t lose it in the middle of the block,
      // but also not causing a strong reference cycle (a.k.a. retain
      // cycle).
    }
};
</code></pre>

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

<p><a href="http://developer.apple.com/library/ios/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011226-CH1-SW4" rel="noreferrer noopener nofollow">Use Lifetime Qualifiers to Avoid Strong Reference Cycles</a> 中的“非平凡循环”讨论中说明了这种模式。在 David 引用的<em>过渡到 ARC 发行说明</em>中。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios -block 如何处理 __weak 引用,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/16470324/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/16470324/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - block 如何处理 __weak 引用