Objective C 中的封装
我对封装有点困惑。一般来说(或在 Obj-C 中),这是否意味着接口/实现的分离,或者是否意味着通过方法访问 ivars?
请澄清。谢谢。
I am a bit confused about encapsulation. In general (or in Obj-C), does it mean separation of interface/implementation OR does it imply access of ivars through methods ?
Please clarify. Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
事实上,两者都有。
正如 nacho4d 所说,您将实例变量封装在类中,并通过使用方法和属性来读取和写入它们的值来防止直接访问它们。这确保了实例始终可以知道某些内容何时读取或写入了值,而直接 ivar 访问与在 C 结构中设置值没有什么不同。
然而,
@interface
与@implementation
的分离也对封装做出了很大贡献。过去几年增强该语言的目标之一是提高这种分离所提供的封装程度。也就是说,该类的主要
@interface
现在可以仅包含您希望其他开发人员/代码与之交互的类部分。公共接口,如果你愿意的话。在最新的编译器中,所有实现细节都可以从@interface 中移出,包括所有实例变量。Actually, Both.
As nacho4d said, you encapsulate instance variables within your class and prevent direct access to them by using methods and properties to read and write their values. This ensures that the instance can always know when something has read or written a value whereas direct ivar access is no different from setting a value in a C struct.
However, the separation of
@interface
from@implementation
also contributes greatly to encapsulation. And one of the goals of the enhancements to the language in the past few years has been to increase the degree of encapsulation offered by that separation.Namely, the class's primary
@interface
can now contain only the parts of your class that you want other developers/code to interact with. The public interface, if you will. All of the implementation details can be moved out of the@interface
in the latest compilers, including all instance variables.后者。来自 维基百科:
具体来说,在 Objective-C 中,ivar 默认情况下将受到 @protected,因此只能在同一类或子类中访问它们。可以根据需要将其更改为@private 或@public。
您提到的方法是访问器(getter 和 setter),在这种情况下您可能想要使用 @properties,因为它们可以在 1 行中定义,并且您可以设置一些属性,如保留、分配、复制、只读等。
进一步了解属性此处(Apple 文档)< /a>
The latter. From wikipedia:
Specifically in Objective-C an ivar will be @protected by default, so they only can be accessed within the same class or subclasses. can change it to @private or @public as you need.
The methods you mentioned are accessors (getters and setters) and in that case you probably want to use @properties since they can be defined in 1 line and you can set some attributes like retain, assign, copy, readonly, etc.
Read further on properties here (Apple doc)
将类方法和变量从一个类隐藏到另一个类称为封装。
Hiding of Class methods and variables from once class to other is called encapsulation.