Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use __attribute__((objc_requires_super)) with protocol

I have something like this:

@protocol MyProtocol <NSObject>

- (void)oneMethod;

@end

.

@interface BaseClassWithProtocol : NSObject <MyProtocol>

@end

.

@interface ChildClassWithProtocol : BaseClassWithProtocol

@end

BaseClassWithProtocol has implemented oneMethod, and I want to show warning if ChildClassWithProtocol doesn't call super in its oneMethod implementation.

But I don't know where should I write __attribute__((objc_requires_super)).

Writing it in protocol is not supported while redefining oneMethod in .h looks stupid.

So is there any standard way which can deal with the problem?

like image 225
Tepmnthar Avatar asked Mar 02 '17 11:03

Tepmnthar


2 Answers

The requirement to call super is imposed by BaseClassWithProtocol. It's not part of the protocol. Surely, some class could implement MyProtocol however it wants without that requirement being imposed. That's the nature of protocols. They impose interface, not implementation.

So, redeclaring the method in BaseClassWithProtocol with the attribute seems perfectly sensible to me. Not sure why it "looks stupid".

like image 134
Ken Thomases Avatar answered Oct 07 '22 21:10

Ken Thomases


Protocols aren't meant to give warnings for your diverse implementations. They only warn you whether you agree to include the required methods in your implementation or not. But how you implement the methods, that's up-to your Base class that adopts the protocol. That is, you should have your necessary functionalities in your .h or .m files.

Consider this way:

You have a method in your protocol where you want to have a warning for the super calls. Now you adopt the protocol in a class which is the sub-class of NSObject. But the NSObject class doesn't conform to the protocol you are defining. Would you now supposed to get the warning for your class? According to your requirements, you should get that warning. But this isn't the case. You would practically never get that warning by this procedure.

like image 42
nayem Avatar answered Oct 07 '22 20:10

nayem