Thursday, March 1, 2012

Objective-C: Hello World!

Hi,
This is the famous (Hello, World!) example using the Objective-C programming language.

 #import <Foundation/Foundation.h>

 int main(int arg, const char * argv[]){

      NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

      NSLog(@"Hello, World!");

      [pool drain];
      return 0;
 }

Explanation:
  • #import:
It's used to include what's in a file (classes, functions, ...) into the program because, the program needs them for whatever it'll do.

The next paragraph is quoted from here.

The final directive we will look at is one you will probably have seen many times already in previous chapters. The #import directive allows you to import include files into your source files. We have done this many times when we have included the Foundation Framework headers in our example programs:

 #import <Foundation/Foundation.h>  

This particular import statement has the path encapsulated by < and > characters. This means that the specified header file is to be found relative to system includes directory (or any other include directories defined for the compilation). To import a header file relative to the directory containing the source file, the file name must enclosed in quotes:

 #import "includes/myincludes.h"  

The above example imports a header file named myincludes.h located in a sub-directory of the current directory called includes. This technique may also be used to specify an absolute path (i.e. one that is not relative to the current directory):

 #import "/Users/demo/objc/includes/myincludes.h"  

  • main:
It's a special function; it's where the program starts execution.
What's between the parentheses are arguments that are passed to the program through the command-line.

  • NSAutoreleasePool / drain:
They are related to the Memory management topic which is out of the scope of this post and they are auto-generated when using Xcode as the development environment.

  • NSLog:
It displays/logs its argument.
Don't forget the @ character before the double quotes.

  • return 0:
(return) ends/terminates the execution.
(0) is the exit status which indicates that the execution has ended normally.

That's it, don't hesitate to comment, to share your knowledge and to correct me.

0 comments:

Post a Comment