insys
insys

Reputation: 1288

Implement protocol through methods declared in superclass?

I'm wondering if it is possible, in a certain subclass, to "recognise" methods declared in it's superclass as implementations of methods declared in a protocol the subclass adheres to, given that they have the same signatures.

It kind of gets hard to even formulate this, that's why any searches I made turned out fruitless so far.

But let me make the case with an example for better understanding.

Protocol:

@protocol TheProtocol <NSObject>

- (void)theProtocolMethod;

@end

Superclass:

// Superclass does not adhere to TheProtocol
@interface TheSuperClass : NSObject

- (void)theProtocolMethod;

@end

@implementation TheSuperClass

- (void)theProtocolMethod
{
    // stuff
}

@end

Subclass:

// SubClass adheres to TheProtocol but does not implement it's methods
// since they are implemented in the class it is subclassing. Is this OK?
@interface TheSubClass : TheSuperClass <TheProtocol>

@end

@implementation TheSubClass

@end

Is this anywhere close to being "OK"?
What about the case TheSubClass was in fact a category of TheSuperClass (declaring adherence to TheProtocol) and not a subclass?

A bit more context:

It's a scenario involving Core Data. I need to publish an accessor defined in an Entity Class, in a Protocol that will be used in a separate Framework for developing plugins for my app. The Protocol itself is fully implemented by a Category of the Core Data Entity Class, except for said accessor which is implemented in the Entity Class itself, hence my question.

Upvotes: 0

Views: 798

Answers (2)

uchuugaka
uchuugaka

Reputation: 12782

In theory you're saying the superclass is already compliant with the protocol.

If the compiler complains, you can implement wrapper methods in your subclass that simply call super and return any return value from the call to super.

Upvotes: 0

stefandouganhyde
stefandouganhyde

Reputation: 4554

In absolute terms, this is perfectly legal. Calling -theProtocolMethod on an instance of TheSubClass would indeed invoke TheSuperClass implementation if TheSubClass itself doesn't implement it. You could even call [super theProtocolMethod] in your subclass implementation, if you wanted.

If TheSubClass was a category on TheSuperClass, the superclass implementation would still be called. However, implementing -theProtocolMethod in the category would replace the super class implementation, so you have to be careful here.

Subjectively, in code-design terms, it's maybe a little odd. You essentially have two separate declarations of the same method to manage, which could potentially cause problems if you tried to refactor. I'm guessing the superclass in your case is a library class that you cannot change. Otherwise, I can't see why TheSuperClass shouldn't just conform to the protocol, rather than declare the method separately.

Upvotes: 1

Related Questions