简体   繁体   English

将__attribute __((objc_requires_super))与协议一起使用

[英]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. BaseClassWithProtocol实现了oneMethod ,如果ChildClassWithProtocol在其oneMethod实现中没有调用super,我想显示警告。

But I don't know where should I write __attribute__((objc_requires_super)) . 但我不知道我应该在哪里写__attribute__((objc_requires_super))

Writing it in protocol is not supported while redefining oneMethod in .h looks stupid. 在.h中重新定义oneMethod看起来很愚蠢时,不支持在协议中编写它。

So is there any standard way which can deal with the problem? 那么有什么标准方法可以解决这个问题吗?

The requirement to call super is imposed by BaseClassWithProtocol . BaseClassWithProtocol强制要求调用super。 It's not part of the protocol. 它不是协议的一部分。 Surely, some class could implement MyProtocol however it wants without that requirement being imposed. 当然,某些类可以实现MyProtocol但它没有强制要求。 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. 因此,使用该属性重新声明BaseClassWithProtocol的方法对我来说似乎是完全合理的。 Not sure why it "looks stupid". 不知道为什么它“看起来很愚蠢”。

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. 但是如何实现这些方法,这取决于采用该协议的Base类。 That is, you should have your necessary functionalities in your .h or .m files. 也就是说, 您应该在.h或.m文件中具有必要的功能。

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. 现在你在一个类中采用协议,这是NSObject的子类。 But the NSObject class doesn't conform to the protocol you are defining. 但是NSObject类不符合您定义的协议。 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. 你几乎不会通过这个程序得到警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM