Brief Introduction to Objective-C
Objective-C is a superset of the C programming language that adds object-oriented constructs. Unlike C++, which was influenced by Simula, Objective-C was influenced by Smalltalk, something we can definitely see in its braces syntax.
Just like C, Objective-C keeps the tradition of separating the source code in two files: a header that defines an interface (.h) and a source file that provides the implementation of said interfaces (.m).
Contrary to popular belief, you do not need a computer running Mac OS X to develop Objective-C programs. The GNUstep project is an open source implementation of the OpenStep reference that provides a basic runtime environment and an implementation of part of the library, including Strings, Arrays and Dictionaries. GNUstep is available for Linux, other UNIX-based OSs and even Windows.
Here’s a short example that defines a 2D point structure with two operations: initialize from a given pair of (x,y) coordinates and printing to stdout.
#import <Foundation/Foundation.h> @interface Point2D : NSObject { float x; float y; } - (id) initWithX:(float)xval andY:(float)yval; - (void) print; @end
Now, we implement this interface in its own file:
#import "point2d.h" #include <stdio.h> @implementation Point2D - (id) initWithX:(float)xval andY:(float)yval; { self = [super init]; if (self) { x = xval; y = yval; } return self; } - (void) print { printf("(%.2f, %.2f)\n", x, y); } @end
Finally, let me show you how to instantiate and send messages to a Point2D object.
#import "point2d.h" int main() { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; Point2D* p = [[Point2D alloc] initWithX:1.0f andY:2.0f]; [p print]; [p release]; [pool release]; return 0; }
Although the Autorelease pool was not really necessary, it is a good practice to have one in place.
If you are trying this example on a Mac, then it’s relatively simple to get it to compile and run. Using GNUstep it gets a little harder however. Here’s a simple Makefile for building this application:
CC=gcc -x objective-c CFLAGS=-I$(GNUSTEP_HOME)/Local/Library/Headers/ -Wall LDFLAGS=-L$(GNUSTEP_HOME)/Local/Library/Libraries/ -lgnustep-base all: $(CC) $(CFLAGS) $(LDFLAGS) main.m