Methods in Objective-C

Our first example demonstrates how to define and use methods in Objective-C. Here’s the full source code:

#import <Foundation/Foundation.h>

@interface Rect : NSObject

@property int width;
@property int height;

- (int)area;
- (int)perim;

@end

@implementation Rect

- (int)area {
    return self.width * self.height;
}

- (int)perim {
    return 2 * self.width + 2 * self.height;
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Rect *r = [[Rect alloc] init];
        r.width = 10;
        r.height = 5;
        
        NSLog(@"area: %d", [r area]);
        NSLog(@"perim: %d", [r perim]);
        
        // In Objective-C, all object variables are pointers
        // so there's no need for separate pointer syntax
        NSLog(@"area: %d", [r area]);
        NSLog(@"perim: %d", [r perim]);
    }
    return 0;
}

In Objective-C, methods are defined within a class interface and implementation. The @interface section declares the methods, while the @implementation section provides their implementations.

The area method calculates and returns the area of the rectangle:

- (int)area {
    return self.width * self.height;
}

The perim method calculates and returns the perimeter of the rectangle:

- (int)perim {
    return 2 * self.width + 2 * self.height;
}

In the main function, we create an instance of Rect and call its methods:

Rect *r = [[Rect alloc] init];
r.width = 10;
r.height = 5;

NSLog(@"area: %d", [r area]);
NSLog(@"perim: %d", [r perim]);

In Objective-C, all object variables are pointers, so there’s no need for separate pointer syntax as in some other languages. Method calls are made using square bracket notation.

To run the program, save it as methods.m and compile it with the Foundation framework:

$ clang -framework Foundation methods.m -o methods
$ ./methods
area: 50
perim: 30
area: 50
perim: 30

Objective-C uses a message passing system for method calls, which is different from function calls in some other languages. This system allows for dynamic dispatch and is a key feature of the language.

Next, we’ll explore how Objective-C handles interfaces and protocols, which are similar to interfaces in other languages.