7.2. Classes and Objects

Objective-C takes the concepts presented in the previous section, and makes minimal extensions to C in order to implement them. Classes in Objective-C are comprised of two basic code structures: the interface block and the implementation block.

The interface block defines the interface of a class, which includes its instance variables and methods. The interface is usually found in a header file, because it should be accessible to the rest of the program. Here is an interface block for a class similar to the Person type defined in the MyAddressBook program from Chapter 6:

@interface Person : NSObject
    NSString *name;
    NSString *address;
-(id)initWithName:(NSString *)name andAddress:(NSString *)address;
-(NSString *)name;
-(NSString *)address;

The interface block begins with the keyword @interface, and ends with @end. After the @interface keyword, the name of the class is given, followed by a colon, and the name of the superclass. The superclass of Person is NSObject, just as Person is a subclass of NSObject. Person inherits all of the data and methods of the class NSObject.NSObject is an important Cocoa class from which nearly all classes ultimately descend. You learn more about this class as you go.

After the superclass, a block in braces declares the data belonging to the class. This part of the class interface is similar in many ways to a C struct, and the preceding code bears a close resemblance to the struct Person used in the ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.