gpt4 book ai didi

ios - 为什么不保留 __block 变量(在非 ARC 环境中)?

转载 作者:可可西里 更新时间:2023-11-01 03:39:22 26 4
gpt4 key购买 nike

我正在阅读 __block variables 上的文档,并思考我使用 __block 的情况。对我来说,似乎在两种情况下我需要它:

  • 在 block 中使用时将变量标记为可读写
  • 在 block 中引用 self 时避免保留循环

从表面上看,这两件事似乎没有关联。我认为 __block 变量不被保留这一事实更多是我需要记住的一个技巧,用于避免保留循环的特定用例。

我想知道,是否有更重要的架构原因不能保留它们?我认为其他一些关键字可以更清楚地表明这一点,以免混淆上面列出的两个功能。

更新 -

我应该提到这是不使用 ARC 的代码。我现在看到 __block 变量实际上保留在 ARC 中。

最佳答案

__block 如果您使用手动引用计数,则不会保留变量。原因可以在这里找到:http://www.mikeash.com/pyblog/friday-qa-2009-08-14-practical-blocks.html :

A simple workaround to this lies in the fact that __block variables are not retained. This is because such variables are mutable, and automatic memory management of them would require each mutation to generate memory management code behind the scenes. This was seen as too intrusive and difficult to get right, especially since the same block may be executing from multiple threads simultaneously.

还有这里:http://lists.apple.com/archives/objc-language/2009/Dec/msg00100.html

There is no way to properly and efficiently manage the retain counts upon re-assignment of the value within the variable.

(我在 Apple 文档中找不到“官方”引用。)

"Transitioning to ARC Release Notes" 中所述,此行为随 ARC 发生了变化:

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.

关于ios - 为什么不保留 __block 变量(在非 ARC 环境中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17384599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com