为什么属性不自动合成 [英] Why don't properties get automatically synthesized

查看:80
本文介绍了为什么属性不自动合成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这是一个愚蠢的问题.每次创建@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屋!

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