>在块中使用时将变量标记为读写
>在块内引用self时避免保留周期
从表面上看,这两件事似乎并不相关.我认为__block变量没有被保留为更多的技巧我需要记住避免保留周期的特定用例.
我想知道,为什么不能保留它们是否有更重要的建筑理由?我会想一些其他关键字来表明这可能更清楚,以免混淆上面列出的两个功能.
更新 –
我应该提到这是不使用ARC的代码.我现在看到__block变量实际上保留在ARC中.
解决方法
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
retainingx
. 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 tonil
to break the retain cycle.