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

我正在阅读 __block variables上的文档,并考虑我使用__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.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...