Data encapsulation ...?

Can anyone explain to me what encapsulation of data is in Objective-C? I was told that this is an important concept of Objective-C, but I do not understand why ...

Explain it to me as if I was 5 years old, and then as if I was 25 years old ....

Thanks for your time, ~ Daniel

+7
objective-c encapsulation
source share
2 answers

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

What we mean by encapsulating data is that the data is contained (so to speak) by methods that have access to it, we need to use methods. Some of you who are programmed in other languages ​​and have not heard of data encapsulation may be wondering why we are doing this the way. The answer is that data encapsulation is a good pillow between a class developer and a class user. Because class methods manage and maintain attributes within a class, they can more easily support Integrity data. Another important advantage is that when a developer distributes his class, people using it do not have to worry about the inner classes at all. The developer may update the way to do it faster or more, but this update is transparent to the user of the class as he still uses the same method without changing his / her code.

Simply put, the user is given what the developer wanted him to have, and β€œprotects” everything else. A developer can change something internal without having to rewrite his code.

If the developers did not match the encapsulation of the data, we will need to rewrite our code each time a new version of the library, a piece of code, or the entire program is released.

+4
source share

Encapsulating data in Objective-C means that only the class itself needs to relate to instance variables. Therefore, you should always mark them as private and only expose them through properties, since 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 setter methods. And it's even better if you use @synthesize to generate your getters and seters, than you don't need to worry about Cocoa's memory model at all (except for freeing your ivars in dealloc).

+3
source share

All Articles