Sunday, December 14, 2008

"Hello, World!", Objective C / Cocoa style

All iPhone development is done in objective-c, so I started to look into objective-c. Hello World!

The following program has been compiled on an Intel based Mac, using the command line:

$ cat hello.h

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
NSLog(@"Hello, World!");
compiling and running:

$ gcc -framework Foundation hello.m
$ ./a.out
2008-12-14 10:41:50.597 a.out[5452:10b] Hello, World!

Differences between objective-c and c++ / java in this example:

1. #import is just like #include. The only difference is that #import is intelligent enough to not include a file more than once.

2. Foundation/Foundation.h: Foundation is the base / core library of programming for iphone / mac. If you need to do anything with cocoa, you need the Foundation "framework". A framework can be thought of as a library. One of the good things Apple did is aggregate all the required headers of all classes in a framework, and made it accessible from one header file. Foundation.h is a huge list of import statements, that gives access to all the class definitions in the Foundation framework.

3. NSLog is the logging function for objective-c/Cocoa. Anything passed to NSLog will be "logged" to stdout.

4. "gcc -framework Foundation hello.m": -framework flag links the binary produced to the Foundation library.

And the rest, as they say, is history :)

No comments:

Post a Comment