How can I make it so that any class that inherits from my base class is forced to override a specific method? I don't want to use a protocol, because that wouldn't make this behavior automated.
@interface MyBaseClass : NSObject { } - (void)performAnAction; @end @implementation MyBaseClass - (void)performAnAction { @throw([NSException exceptionWith...]); } @end
Just declare the method as abstract in the base class. All children classes will then be forced to implement it. Alternatively you could also use an interface instead of a concrete class, which is simply an agreement that the methods defined will be implemented.
It has all of the instance variables. The only unusual aspect is that, within child class method definitions, you can't directly access parent class instance variables. For example, if the parent had a height instance variable, child class method definitions wouldn't be able to access this directly.
You must override your method from parent class only of you want to override super class. But you must override every methodsfrom Iterface when you implement it by some of your class.
If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.
How exactly do you mean, force them to override it? If you simply implement the parent method like so:
- (void)performAction { NSAssert(NO, @"The method %@ in %@ must be overridden.", NSStringFromSelector(_cmd), NSStringFromClass([self class])); }
then it'll throw an exception at runtime if the child class fails to override it. Unfortunately there is no way to enforce this at compile-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With