As a C#/Java Programmer I’m having a hard time getting the following problem solved:
There is a base class “B”. In its init Method it calls a method “SetupStuff”.
For the base class this method is just empty.
Then there is a derived class “D” that inherits from “B”.
D implements the method “SetupStuff”, too (and actually does something there).
The problem is: When I create an object of D, its “SetupStuff” is never called. The init method of B is called, then the empty “SetupStuff” of is called.
What would I need to do to make the derived class’s method being called?
If you are trying to invoke an override from inside your initializer, it is not going to work. The reason for it is easy to understand: since the override belongs to a subclass, and because the superclass instance initialization needs to be complete before the subclass initialization can start, calling a derived method would have violated the rules that by the time a “regular” method is called the initialization of the instance has completed. Generally, calling virtuals from Java or C# constructors is not a good idea, for the same exact reason. In C++, calling virtuals from a constructor redirects to the implementation in the cosntructor’s own class (i.e. the same thing that you observe in Objective C).
Unlike C# and Java where overriding static methods is not allowed, Objective C lets you provide class-specific implementations of class methods. You can use this mechanism to achieve what you are trying to do: define a class method in the derived class, and call it from the base class, like this:
When you call
you see
in the log.