Online Training Spring Hibernate Training in Delhi R Programming Training Course Big Data and Hadoop Training Java Training

Objective C Constructors

Objective-C enables user to define constructor with the help of self and super keywords.

Ads

Objective C Constructors

     

Objective-C enables user to define constructor with the help of self and super keywords. Like java Objective-C has parent class and programmer can access its constructor by statement [super init], this statement returns a instance of parent class which we assign to the 'self' keyword, actually 'self' plays same role as this keyword in C++ and Java. The default constructor is -(id) init statement if(self) is used to check the condition self != nil to confirm that parent class returned a new object successfully.

Example:

MyClass.h
#import<Foundation/NSObject.h>
@interface MyClass:NSObject{
int a;
int b;
}
// declare constructor
-(MyClass*) set:(int) a andb:(int) b;
-(void) sum;
@end

MyClass.m

#import<stdio.h>
#import"MyClass.h"
@implementation MyClass
// define constructor
-(MyClass*) set:(int) x andb:(int) y {
  self = [super init];
  if(self) {
    a=x;
    b=y;
    return self;
}
}
-(void) sum {
printf("Sum is : %d",a+b);
}
@end

MyClassMain.m

#import<stdio.h>
#import"MyClass.m"
int main(){

// use constructor
MyClass *class = [[MyClass alloc] set : 10 andb : 12];
[class sum];
[class release];
return ;
}

Output:

Sum is : 22

Advertisements

Ads
Share on Google+Share on Google+

Objective C Constructors

Posted on: May 24, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: Objective C Constructors   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:2
Ryan
December 29, 2011
Wrong code

-(MyClass*) set:(int) x andb:(int) y { self = [super init]; if(self) { a=x; b=y; return self; } -(MyClass*) set:(int) a andb:(int) b; Do not match. The method argument should be -(MyClass*) set:(int) x andb: (int) y;
Anirban Roy
July 13, 2012
Objective C

Hi Team, I am very new in this technology .I want to learn the technology properly .Please help me sending anything that relates TO ANY VALID BASIC Objective C . Thanks & Regards, Anirban Roy

Ads

 

Ads