Objective-C Program Structure

An Objective-C program generally consists of the these parts:

  • Preprocessor Commands
  • Interface
  • Implementation
  • Comments
  • Method
  • Statements & Expressions
  • Variables

Objective-C Program Structure Example

Here is an example program to understand the basic structure of an Objective-C program:

/* Objective-C Program Structure - Example Program */
#import <Foundation/Foundation.h>
@interface SampleClass:NSObject
- (void)sampleMethod;
@implementation SampleClass
- (void)sampleMethod
   NSLog(@"Hello, World \n");
int main()
   SampleClass *sampleClass = [[SampleClass alloc]init];
   [sampleClass sampleMethod];
   return 0;

How to Compile and Execute an Objective-C Program ?

When the above program is compile and executed, it would produce the following result:

2009-06-03 13:18:37.932 demo[28001] Hello, World

Now let's look at various parts of the above program :

  • The very first line, i.e., /* Objective-C Program Structure - Example Program */ is a comment
  • The next line of the above Objective-C program, ie. #import <Foundation/Foundation.h> is a preprocessor command, tells an Objective-C compiler to include the Foundation.h file before going to the actual compilation
  • The next line @interface SampleClass:NSObject simply shows how to create an interface. It inherits an NSObject, which is the base class of all the objects
  • The next line - (void)sampleMethod; shows how to declare a method
  • The next line @end marks the end of an interface
  • The next line @implementation SampleClass shows how to implement the interface SampleClass
  • The next line - (void)sampleMethod{} shows the implementation of the sampleMethod
  • The next line @end marks the end of an implementation
  • The next line int main() is the main function where the program execution begins
  • The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program
  • The next line NSLog(...) is an another function available in Objective-C which causes the message "Hello, World!" to be displayed on the screen
  • The next line return 0; terminates the main() function and returns the value 0

Objective-C Online Test

« Previous Tutorial Next Tutorial »