Methods in Objective-C
Our first example demonstrates how to define and use methods in Objective-C. Here’s the full source code:
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:
The perim
method calculates and returns the perimeter of the rectangle:
In the main
function, we create an instance of Rect
and call its methods:
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:
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.