Reputation: 447
MySubClass.h
@interface MySubClass : NSObject
{
}
MySubClass.m
@interface MySubClass ()
@end
@implementation MySubClass
-(MySubClass*)initMySubClass:(id)view{
// initialize my SubClass
}
@end
What is the proper way to write a custom initializer if I subclass from NSObject?
Do I need to use "init" inside my initializer?
Upvotes: 1
Views: 628
Reputation: 2213
@michaelrccurtis's answer is correct. But here's more thorough documentation on how you generally do initialization in Obj-C.
Basically, every class can have a designated initializer and if you subclass it, you must override that initializer and call super from your subclass's designated initializer. The graphic in the docs makes this clearer.
Upvotes: 0
Reputation: 1172
-(instancetype)initMySubClass:(id)view {
if(self = [super init]) {
// custom initialization here
}
return self;
}
Apple docs are here: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/index.html#//apple_ref/occ/instm/NSObject/init
Note that, for NSObject
itself, the init
method just returns self
. It is still best practice to call init
, however. For example, what if Apple were to include additional initialisation there in the future? Or, what if you want to change the superclass?
Upvotes: 1