Stas
Stas

Reputation: 641

How to make all subclasses necessarily conform to protocol?

I have a base class SLBaseViewController which is a subclass of UIViewController and want all its subclasses to conform to protocol:

@protocol SLLocalizable <NSObject>

- (void)localize;

@end

The problem is that I don't need SLBaseViewController to conform to protocol itself, but I need compiler to warn me if a subclass doesn't conform.

What I have tried:

  1. Define base class like this:

    @interface SLBaseViewController : UIViewController <SLLocalizable>
    

    In this case compiler tells me that SLBaseViewController does not implement localize method.

  2. Make localize optional.

    Compiler keeps silence. But that's not what I need.

  3. Make each of subclasses conform to protocol itself. That seems to be a right way, but I have more than 50 subclasses and it's a long way.

Is there a simple way to reach my goal?

Upvotes: 2

Views: 685

Answers (2)

newacct
newacct

Reputation: 122449

In what case would you need all subclasses to implement something, but don't need the common superclass to implement it?

If it is that SLBaseViewController is an abstract class that is not meant to be instantiated directly, you can simply have it implement -localize, and in the body throw an exception. Or, you can simply ignore the warning (it is just a warning after all).

Upvotes: 1

Wain
Wain

Reputation: 119031

You can't specify that the subclasses implement any protocol other than to specify it in the subclass itself.

Search for the subclasses to edit them (rather than trying to remember each). A reflex search would be able to find subclasses which don't give the protocol name.

As a safety check, make the superclass throw an exception if it's called so you know when you missed something. Obviously this only works during testing.

If this makes you paranoid, you could try writing a unit test which gets all the subclasses and calls localize on them.

Upvotes: 1

Related Questions