Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Subclassing and compulsory methods

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

like image 754
Dann Avatar asked Nov 06 '12 12:11

Dann


2 Answers

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.

Example

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.

like image 121
Richard Stelling Avatar answered Oct 23 '22 23:10

Richard Stelling


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)];
like image 20
Rengers Avatar answered Oct 24 '22 00:10

Rengers