数据封装...?
谁能向我解释一下 Objective-C 中的数据封装是什么?有人告诉我这是 Objective-C 的一个重要概念,但我不明白为什么...
向我解释一下,就像我 5 岁,然后就像我 25 岁一样...
感谢您的时间, ~丹尼尔
Would anyone be able to explain to me what data encapsulation in Objective-C is? I've been told that this an important concept of Objective-C but I don't see why...
Explain it to me as if I was 5 and then as if I was 25....
Thanks for your time,
~Daniel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 http://mobile.tutsplus.com/tutorials/iphone/learn -objective-c-2/:
简而言之,向用户提供开发人员希望他们拥有的东西,并“保护”其他一切。开发人员可以更改任何内部内容,而无需用户重写其代码。
如果开发人员不遵守数据封装,那么每次发布新版本的库、代码片段或整个程序时,我们都需要重写代码。
From http://mobile.tutsplus.com/tutorials/iphone/learn-objective-c-2/ :
In simple terms, the user is provided with what the developer wanted them to have, and "protects" everything else. The developer can change anything internal without the user having to rewrite their code.
If developers did not conform to data encapsulation, we would need to rewrite our code every time a new version of a library, code snippet, or an entire program was released.
Objective-C 中的数据封装意味着只有类本身才能接触它的实例变量。因此,您应该始终将它们标记为私有,并且仅通过属性公开它们,如下所示:
这意味着该类可以在其 setter 方法中实现验证。如果您使用 @synthesize 来生成 getter 和 setter,那就更好了,您根本不需要担心 Cocoa 的内存模型(除了在 dealloc 中释放 ivars 之外)。
Data encapsulation in Objective-C means that only the class itself should touch it's instance variables. Therefor you should always mark them as private, and only expose them through properties, as this:
This means that the class can implement validation in it's setter methods. And even better if you use
@synthesize
to generate your getter and setters than you need not even worry about the memory model of Cocoa at all (with the exception of releasing your ivars in dealloc).