Question

What is the purpose of the initializer pattern other then in order to assure that the object is properly initialized by its superclass before the init method performs its initialisation.

Why is this necessary?

and

when we have a class which has more than one initialization method, why others shoud call the dedicated initialiser instead of superclass initialiser?

I'm coming from java background so don't fully understand this - the closest i could match in java was singleton pattern but the part others calling dedicated initialiser didn't make sense to me as in java you have a choice rather then you "should".

can any one elaborate....thx

Was it helpful?

Solution

  1. The initializer pattern is necessary, because the super class whose initializer you are calling, can return any kind of object, not necessarily the instance of that class. That's how, for example, NSString works, it's actually a cluster of classes implementing different kinds of strings optimized for different usage patterns. So calling self = [super init] for NSString descendant makes self, for example, an NSCFString instance.

  2. There's a pattern called Designated Initializer in Objective C. If the class has many initializer, one of them is chosen as designated, and all the other should be implemented by calling it, not the super. This is important for correctly overriding initializers in child classes, you should initialize only the designated one, and it will be called under all circumstances (assuming your code is well-written and takes advantage of designated initializers, of course :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top