Last Updated: February 25, 2016
·
606
· krzyzanowskim

Default initializer in Objective-C

Overriding initializers in Objectice-C is allways paint in the ass. This is because when you inherit class with you custom one, you need override ALL initializers, there is no single one root initializer.

So if you want to set something inside initializer, you have to find all of them and override. This is how Cocoa is build, but I don't think this is the best approach.

What I do is allways call [self init], instead [super init] in initialisers other than init itself.

Like this:

- (instancetype) init
{
    if (self = [super init]) {
        // do some common work here
        // self.string = @"Name"
    }
    return self;
}

- (instancetype) initWithString:(NSString *)string
{
    if (self = [self init]) {
        // do something, default value for self.string is set already
    }
    return self;
}

I really like this pattern.