Angus Angus - 3 months ago 11
Objective-C Question

Constructor in Objective C

I am beginner in iPhone development.I was trying this sample program below.

I'm not calling the +(void)initialise and -(id)init method in the class B.But its getting called automatically.

Is the -(void)intialise is equal to the default constructor in objective C.

Does the [super init] points to the NSObject.

If i'm not using the -(id)init method i'm getting a warning that the class is with incomplete implementation.

ClassA.h

#import <Foundation/Foundation.h>

static int ab;

@interface ClassA : NSObject {
int a;
}

+ (void) initialize;
- (id) init;
- (void) displayNumOfInstance;
- (void) disp;

@end


ClassA.m

#import "ClassA.h"

@implementation ClassA

+ (void) initialize
{
ab=0;
}

- (id) init
{
self = [super init];
if (self!=nil) {
ab++;
}
return self;
}

- (void) displayNumOfInstance
{
NSLog(@"Number of instances of this class:%d",ab);
}

- (void) disp
{
NSLog(@"The value is %d",ab);
}

@end


ClassB.h

#import <Foundation/Foundation.h>
#import "ClassA.h"

@interface ClassB : ClassA {

}

- (void) display;

@end


ClassB.m

#import "ClassB.h"

@implementation ClassB

- (void) display
{
ab=20;
NSLog(@"The value ab is %d",ab);
}

@end


class2.m

#import <Foundation/Foundation.h>
#import "ClassA.h"

int main (int argc, const char * argv[]) {
ClassA *a = [[ClassA alloc]init];
[a disp];
[a release];

ClassB *b = [[ClassB alloc]init];
[b display];
[b release];

ClassA *a1 = [[ClassA alloc]init];
[a1 disp];
[a1 release];

ClassB *b1 = [[ClassB alloc]init];
[b1 display];
[b1 release];

return 0;
}


Output:

2011-04-30 15:31:42.490 class2[1674:a0f] 1
2011-04-30 15:31:42.493 class2[1674:a0f] The value ab is 20
2011-04-30 15:31:42.494 class2[1674:a0f] 2
2011-04-30 15:31:42.495 class2[1674:a0f] The value ab is 20

Answer

The default construction usually start with has the following format - (id)init or any variant upon this, e.g. - (id)initWithFrame:(CGRect)frame. The method + (void)initialize is a class method (static method) that's called at least once when your application starts. You can use this method to initialize static variables that are useful across all instances of the class, though usually you will just implement the - (id)init method for any instance. Indeed - (id)init is the default initializer for an instance of a class. Whenever initializing an object, make sure to initialize it's super class as well, e.g.

- (id)init 
{
    self = [super init];
    if (self) 
    {
        // superclass successfully initialized, further 
        // initialization happens here ...
    }
    return self;
}

If the object inherits from NSObject, then the - (id)init method of NSObject will be called. This way you can be sure you have access to e.g. all instance methods of NSObject or whatever your superclass is.