advertisement

Article:
  The Objective-C Language
Subject:   Calling [super init] within your own initXXX methods
Date:   2001-07-04 20:13:20
From:   bigboytoddy
Response to: IMHO the right way to do setter selector definitions

Hello again.


It was pointed out that your method for init (custom derivations and default initializer) would look like this for the class Circle...


@interface Circle : SomeOtherClass
{
double radius; // should be NSNumber IMHO
}
- initWithRadius: (double)r;
@end


@implementation Circle
- initWithRadius: (double)r
{
radius = r;
}
@end


In reality, this could and likely will be troublesome. It assumes there is no additional initialization done by the parent class... Bad assumption, really bad.


The correct way to define a default initializer method is more like


- init
{
return ( [self initWithX: defaultValueForX ] );
}


// This is the designated init method for this class
- initWithX: valueHolderForX
{
[super init]; // us the default initializer for the super class, init can be assumed, yet it would help to know your parent implementation since indeed you are inheriting functionality from it, makes sense to know it. There may be specific default initializers that are more useful and appropriate for your use.
// set your iVars here
x = valueHolderForX;
[ ... maybe private iVars are set here ... ]
}


Hope this helps.


\t