为什么属性不自动合成 [英] Why don't properties get automatically synthesized
问题描述
也许这是一个愚蠢的问题.每次创建@property
时,都必须@synthesize
.但这对@property(whatever) Type* property
唯一可以做的就是在实现文件中执行@synthesize property
是没有道理的.那么为什么两者都需要呢?为什么不用我不必编写@synthesize property
,编译器就不会自动生成getter/setter方法.
在当前的生产编译器中,默认设置(不带@synthesize
的情况)不执行任何操作,然后在未提供实现的情况下发出警告.
@synthesize
在LLVM 2.0编译器的最新版本中是自动的.
@dynamic
.在运行时动态提供实现时使用@dynamic
.也就是说,如果不提供-foo
和-setFoo:
实现,则@dynamic foo;
与@property <type> foo;
结合使用将导致编译器不警告.
请注意,您还可以使用@synthesize propertyName = instanceVariableName;
来使用特定的,名称不同的实例变量作为后备存储.
@property
在很大程度上是getter/setter方法声明的简写.它还携带了更多元数据(保留,分配等),编译器在@synthesize
期间利用了这些元数据.
而且,与往常一样,atomic
属性对线程安全性并没有真正帮助.
maybe this is a silly question. Every time I make a @property
I have to @synthesize
it. But this makes no sense the only thing you can do with a @property(whatever) Type* property
is to do @synthesize property
in the implementation file. So why are both needed? Why isn't the compiler generating the getter/setter methods automagically without me having to write @synthesize property
.
In the current production compilers, the default -- the case without @synthesize
-- is to do nothing and then warn if an implementation isn't provided.
@synthesize
is automatic in the latest versions of the LLVM 2.0 compiler.
@dynamic
is not required when implementing the setter/getter yourself. @dynamic
is used when dynamically providing the implementations at runtime. That is, @dynamic foo;
combined with @property <type> foo;
will cause the compiler not to warn if you don't provide a -foo
and -setFoo:
implementation.
Note that you can also use @synthesize propertyName = instanceVariableName;
to use a specific, differently named, instance variable as the backing store.
@property
in the interface very much is short hand for the getter/setter method declarations. It also carries more metadata (retain, assign, etc..) that is leveraged by the compiler during @synthesize
.
And, as always, an atomic
property doesn't really help with thread safety.
这篇关于为什么属性不自动合成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!