Purpose of init pattern in obj-c and its use
-
14-04-2021 - |
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
Solution
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 callingself = [super init]
forNSString
descendant makes self, for example, anNSCFString
instance.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 :)