需要实现一组方法中的至少一个的目标 C 协议 [英] Objective C protocols requiring the implementation of at least one of a set of methods
问题描述
在目标 C 中,协议方法可以是必需的或可选的:
In Objective C, protocol methods can be required or optional:
@protocol AProtocol
@required
-(void) aRequiredMethod;
@optional
-(void) anOptionalMethod;
@end
有没有一种优雅的方式说符合协议的对象必须至少响应一组方法中的一个,我的梦想是这样的
Is there an elegant way to say the object conforming to the protocol has to respond to at least one of a set of methods, my dream would be something like
@protocol AProtocol
@anyof
-(void) onePossibleMethod;
-(void) anotherPossibleMethod;
@optional
-(void) anOptionalMethod;
@end
这是(据我所知)不可能的,如果一个类声明为符合完全由可选方法组成的给定协议,是否有办法引发编译时警告
This being (as far as I know), impossible, would there be a way to raise a compile time warning if a class declared as conforming to a given protocol made entirely of optional methods
@protocol AProtocol
@optional
-(void) onePossibleMethod;
-(void) anotherPossibleMethod;
@end
未能实现其中至少一项.
failed to implement at least one of them.
推荐答案
在 Objective-C 中没有一种很好的方式来表达这一点.如果你必须这样做,IMO 最惯用和最少代码膨胀的方式是这样的:
There isn't a great way to express this in Objective-C. If you must do this, IMO the most idiomatic and least code-bloating way is something along these lines:
@protocol AProtocol
@required
- (SEL)methodToUse; // returns one of "onePossibleMethod" or "anotherPossibleMethod"
@optional
-(void) onePossibleMethod;
-(void) anotherPossibleMethod;
-(void) anOptionalMethod;
@en
这篇关于需要实现一组方法中的至少一个的目标 C 协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!