Pages

Tuesday, May 18, 2010

Objective-C "explained".

The most boring program in the world is "Hello, World!". Here is the C-variant of this program:

#include <stdio.h>

int main (int argc, const char * argv[])
{
printf("Hello, World!\n");
return 0;
}

Same program in Objective-C looks so:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

printf("Hello, World!");

[pool drain];
return 0;
}

The difference is not very big:
1. #import instead of #include. #include will work too. #import ensures that the header file is included only once. It is a replacement for our common

#ifdef _MY_HEADER_FILE_H_
#define _MY_HEADER_FILE_H_


#endif

2. Object instantiation:
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

I can replace this code with:
NSAutoreleasePool * pool = [NSAutoreleasePool new];

The program compiles and works with this replacement. Any C++ programmers understand what it does.

This trivial example explains the main principles of Objective-C:
1. The letter 'C' is the last in the name, but the the most important. Objective-C is a superset of C. Standard C functions can be called from the Objective-C code.
2. Objective-C is an extension of C. Strong and extremely portable procedural language C was updated by adding the message-send mechanism from SmallTalk, so we got [object message], instead of the common object->messaqe in C++. n C++ the program will crash if the object is NULL. In Objective-C it will not crash, if the object is nil.

No comments:

Post a Comment