Reputation: 26223
Can you create a custom initialiser for a class without over-riding init?
Can you for example do:
+ (instancetype)node {
BetterSKNode *newNode = [[BetterSKNode alloc]initWithRootName:@"ROOT"];
return newNode;
}
- (id)initWithRootName:(NSString *)rootName {
self = [super init];
if(self) {
_rootName = rootName;
}
return self;
}
if you do should the above be self = [super init];
or self = [self init];
its easy to add (see below), but I was just curious if its necessary?
- (id)init {
self = [super init];
if(self) {
// ...
}
return self;
}
Technically the correct approach would be to call the "designated initialiser" from init to cover the possibility that someone may in the future just call [[Class alloc]init]
- (id)init {
self = [self initWithRootName:@"ROOT"];
return self;
}
Upvotes: 0
Views: 49
Reputation: 150745
The convention in Cocoa is to have a designated initialiser, which is the initialiser that all the other initialisers call. It is usually the initialiser with the most parameters (because these can be set to default values by the other initialisers)
Further, this designated initialiser should call it's superclass's designated initialiser as part of it's implementation.
So in your case, you already have a designated initialiser in initWithRootName:
so your code could look like:
+ (instancetype)node {
BetterSKNode *newNode = [[BetterSKNode alloc]initWithRootName:@"ROOT"];
return newNode;
}
- (id)initWithRootName:(NSString *)rootName {
self = [super init]; // Assuming that init is the designated initialiser of the superclass
if(self) {
_rootName = rootName;
}
return self;
}
// If you choose to add an init, method then it should call the designated initialiser
- (id)init {
return [self initWithRootName:@"ROOT"]; // use a default value for the parameter
}
So yes, you can subclass without overriding init
.
Upvotes: 1
Reputation: 130201
Of course you can do it, if we suppose you are inheriting from NSObject
. NSObject
implements -(id)init
and that method is inherited to the subclasses.
Upvotes: 1
Reputation: 119041
Using self = [self init];
protects you against future changes where you add an init
method to the class, but you can add it when you refactor in the future.
Note that you don't need to implement the method because it will dispatch up to super
. If you aren't doing anything custom, don't add the extra code.
Upvotes: 1