Thursday, July 18, 2013

Class and Method declaration and definitions


Because of objective-C is the extension of ANSI-C and it follows an object oriented approach so provides classes and objects. The way to declare and define classes and creation of object is little bit different from C and C++.
To declare a new class objective-C uses @interface directive.
Declaration of a simple class: MyClass.h

#import"SuperClass.h"
#import
@interface ClassName:SuperClass {
variable daclaration;
variable daclaration;
}
method declaration;
method declaration;
@end #import

@interface MyClass:NSObject{
int a;
int b;
}
-(void) setvara : (int) x;
-(void) setvarb : (int) y;
-(int) add;
@end
Definition of declared class: MyClass.m
#import
#import"MyClass.h"

@implementation MyClass
-(void) setvara :(int) x{
a=x;
}
-(void) setvarb :(int) y{
b=y;
}
-(int) add{
return a+b;
}
@end
Piecing it together
main.m
#import
#import"MyClass.m"

int main(){
MyClass *class = [[MyClass alloc]init];
[class setvara : 5];
[class setvarb : 6];
printf("Sum is : %d",[class add]);
[class release];
return ;
}

Compiling Objective C on windows
Go to the directory where hello.m example program is saved. You can use the following command.
$ cd c:/objectiveC


To compile program run the following command
$ gcc -o hello hello.m


This command will create a executable file of given name (here 'hello').
To run the program

$ ./hello

No comments:

Post a Comment