微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐