属性声明中的__block属性 [英] __block attribute on property declarations

查看:117
本文介绍了属性声明中的__block属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须修复一些现有的代码,这些代码在LLVM(iOS上)下可以很好地构建,因此它也可以使用llvm-gcc-4.2进行构建。我完成了几乎所有的事情,除了在几个地方发现的这种模式外:

  @property(nonatomic,retain )__block id myProperty; 

我怀疑这里的意图是允许从块中访问属性而不保留。我该如何删除 __ block 属性,这个gcc在这里不支持,但仍然达到相同效果?

  

@property(nonatomic,retain)__block id myProperty;

没有意义。 __ block 限定符用于本地(堆栈分配)变量,因此它们通过引用传递给块,所以它们可以更新,并且通常[*]存储在堆中而不是堆栈。

因此,限定符 __ block 对与对象实例有关的属性声明没有意义,它们始终是在Obj-C中分配的堆。

只需从属性声明中删除 __ block 对于每一个编译器来说。

如果一个块永远不会被复制到堆中,编译器可能会优化__block变量并且不会将它们移动到堆中。


I have to fix some existing code that builds just fine with LLVM (on iOS) so that it builds with llvm-gcc-4.2 too. I'm done with pretty much everything, except this pattern which is found at a few places:

@property (nonatomic, retain) __block id myProperty;

I suspect the intent here is to allow access to the property from inside a block without retaining self. How can I remove the __block attribute, which gcc doesn't support here, but still achieve the same effect?

解决方案

I'll suggest you've found a compiler bug, the declaration:

@property (nonatomic, retain) __block id myProperty;

is meaningless. The __block qualifier is used on local (stack allocated) variables so they are passed by reference to blocks, so they can be updated, and are usually[*] stored on the heap rather than the stack.

Therefore the qualifier __block has no meaning on a property declaration which is concerned with object instances, which are heap allocated at all times in Obj-C.

Just drop the __block from the property declarations - for every compiler.

[*] If a block is never copied to the heap a compiler may optimize __block variables and not move those to the heap either.

这篇关于属性声明中的__block属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆