7.4. Data Hiding

An important aspect of OOP is encapsulation of data. Encapsulation requires that a language include facilities for data hiding so that the programmer can control access to data from outside a class. Objective-C provides three keywords for this purpose: @public, @protected, and @private. These keywords can be inserted into the data section of a class's interface block and applies to any data that follows, up to the end of the block or the next keyword.

For example, imagine that you want to restrict access to the name attribute of the Person class, but wish to make the address attribute directly accessible to the rest of the program. You could declare the class like this:

@interface Person : NSObject
{
    @public
    NSString *address;

    @private
    NSString *name;
}
...
@end

The @public keyword makes an instance variable globally accessible. Any part of your program can directly retrieve the value of a public variable or modify its value. The @private keyword indicates that data may be accessed only from within the specific class in which it appears, in this case Person. @protected gives access to the data from within the class in which it appears, but also from descendents of that class—subclasses of the class, subclasses of subclasses of the class, and so forth. If no keyword is given, instance variables are assumed to have protected accessibility.

In general, you should make as much data in your classes protected or private as possible. Public data is frowned upon in OOP, ...

Get Beginning Mac OS® X Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.