Objective-C 属性问题
我是 Objective-C 的新手,一直想知道创建属性有什么意义?我可以在标题中创建一个变量吗?为什么要创建同名的变量和属性?
I'm new to objective-c and have been wondering what's the point of creating properties? I can just create a variable in the header? Why create a variable and a property with the same name?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更轻松的内存管理(对于某些人),更好的设计(对于所有人)。属性使类的公共接口变得具体,并且它定义了弱引用和强引用。
Easier memory management (for some), better design (for all). Properties make your public interface to the class concrete, and it defines what is weakly and what is strongly referenced.
作为 Joshua 所说的补充:属性是 KVC /KVO 兼容,而变量不兼容,整个 Cocoa 都基于 KVO。您可以将属性绑定到属性,可以添加观察者,可以免费使用 valueForKey/valueForKeyPath 及其“set”兄弟。如果必须发布该值(即可用于外部类)-创建一个属性,您将免费获得很多东西。只需确保您已设置正确的内存管理选项(分配、复制或保留)和线程安全修饰符(非原子)。
As an addition to what Joshua have said: properties are KVC/KVO-compatible while variables are not, whole Cocoa stands on KVO. You can bind a property and to property, you can add an observer, you can use valueForKey/valueForKeyPath and their 'set' brothers for free. If the value must be published (i.e. available for external classes) - make a property, you will get a lot of stuff for free. Just make sure you've set the proper memory management option (assign, copy or retain) and thread-safety modifier (nonatomic).