声明私有成员变量
我几周前开始学习 Objective-C,但我仍然不明白如何正确管理类的封装。在类中声明私有成员变量的最佳方法是什么?
看来,使用“@property”为成员变量设置正确的 getter/setter 是正确的方法,而不仅仅是在界面中声明它“@private”。但在我看来,这仍然让其他类可以访问这些变量。即使您将属性声明为“只读”,外部类也可以访问对成员变量的引用并修改它!
所以我猜测声明私有成员变量的最佳方法是通过不声明属性来不包含任何 getter/setter。我说得对吗?或者有更好的方法吗?
谢谢
I've started learning Objective-C a few weeks ago and I still don't understand how to manage the encapsulation of a class correctly. What is the best way to declare a private member variable in a class?
It seems that setting the right getter/setter for your member variable with "@property" is the right way to go, more than just declaring it "@private" in the interface. But it seems to me that this still gives other classes an access to these variables. Even if you declare the property "readonly", an outside class can access the reference to the member variable and modify it!
So I'm guessing the best way to declare a private member variable is to not include any guetter/setter by not declaring a property. Am i right? Or is there a better way?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您不希望其他类可以访问它,请在您的实现上声明 @property,为您的类创建一个匿名类别。
头文件:
实现:
这些是三个不同属性的示例。
if you don't want it accessible to other classes, declare the @property on your implementation, creating an anonymous category for your class.
Header file:
Implementation:
These are examples of three different properties.