I have a base view controller that a number of other view controllers subclass. Is there a way of enforcing certain methods which have to be overridden in a subclass?
For safety sake more than anything.
Cheers
In Xcode (using clang etc) I like to use __attribute__((unavailable(...)))
to tag the abstract classes so you get an error/warning if you try and use it.
It provides some protection against accidentally using the method.
In the base class @interface
tag the "abstract" methods:
- (void)myAbstractMethod:(id)param1 __attribute__((unavailable("You should always override this")));
Taking this one-step further, I create a macro:
#define UnavailableMacro(msg) __attribute__((unavailable(msg)))
This lets you do this:
- (void)myAbstractMethod:(id)param1 UnavailableMacro("You should always override this");
Like I said, this is not real compiler protection but it's about as good as your going to get in a language that doesn't support abstract methods.
In other languages this is done using abstract classes and methods. In Objective-C there is no such thing.
The closest you can get is raising an exception in the superclass so subclasses are 'forced' to override them.
[NSException raise:NSInternalInconsistencyException format:@"Subclasses must override %@", NSStringFromSelector(_cmd)];
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