views:

44

answers:

2

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  A: 

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.

Evan Mulawski
A: 

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 sue @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).

PeyloW