Data encapsulation…?

走远了吗. 提交于 2020-01-12 18:36:43

问题


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


回答1:


From http://mobile.tutsplus.com/tutorials/iphone/learn-objective-c-2/ :

What we mean by data encapsulation is that data is contained (so to speak) by methods meaning to access it we need to use methods. Some of you who have programmed in other languages and havenʼt heard of data encapsulation may be wondering why we do things this way. The answer is that by encapsulating data, there is a nice cushion between the developer of a class and the user of a class. Because the class methods manage and maintains the attributes within the class, they can more easily maintain data integrity. Another major benefit is that when a developer distributes his class, the people using it donʼt have to worry about the internals of the class at all. A developer may update a method to make it faster or more efficient, but this update is transparent to the user of the class as he/she still uses the same method with no change to his/her code.

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.




回答2:


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:

@interface Foo : NSObject {
@private
    int numberOfBars;
    Baz* contentBaz;
}
@property(nonatamic, assign) int numberOfBars;
@property(nonatomic, retain) Baz* contentBaz;
@end

This means that the class can implement validation in it's setter methods. And even better if you use @synthesizeto 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).



来源:https://stackoverflow.com/questions/4004768/data-encapsulation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!