13. Classes, Objects, and Ties


// A class has a header part traditionally named HumanCannibal.h in that case...
#import <Foundation/Foundation.h>
@interface HumanCannibal : NSObject {
    // instance variables
    NSString *stomach;
    NSString *place;
- (void) feed: (NSString*) input;
- (void) move: (NSString*) input;
+ (void) classOnlyMethod;
// ...and an implementation part named HumanCannibal.m in that case
#import "HumanCannibal.h"
@implementation HumanCannibal
- (void) init {
    // this is the constructor. do whatever but don't forget to
    // call the parent constructor!
    [super init];
- (void) feed: (NSString*) input {
    stomach = input;
- (void) move: (NSString*) input {
    place = input;
- (NSString*) description {
    return [NSString stringWithFormat: @"In %@, stomach contains %@", place, stomach];
+ (void) classOnlyMethod {
    // do whatever

// method calls are between square brackets
#import "HumanCannibal.h"
int main(void) {
    HumanCannibal *lector = [HumanCannibal new];
    NSLog(@"%@", lector);
    [lector feed: @"Zak"];
    [lector move: @"New York"];
    NSLog(@"%@", lector);
// # gcc -x objective-c -Wno-import HumanCannibal.m main.m -lobjc -lgnustep-base -fconstant-string-class=NSConstantString && ./a.out 
// 2010-07-02 13:19:47.954 a.out[8288] In (nil), stomach contains (nil)
// 2010-07-02 13:19:47.958 a.out[8288] In New York, stomach contains Zak

Constructing an Object

Destroying an Object

Managing Instance Data

Managing Class Data

Using Classes as Structs

Cloning Objects

Calling Methods Indirectly

Determining Subclass Membership

Writing an Inheritable Class

Accessing Overridden Methods

Generating Attribute Methods Using AUTOLOAD

Solving the Data Inheritance Problem

Coping with Circular Data Structures

Overloading Operators

Creating Magic Variables with tie