假设我已经为子类 UIView
定义了一个协议(protocol),如下所示:
@protocol MyCustomViewDelegate <NSObject>
- (NSString*) titleForItemAtIndex;
- (UIImage*) imageForItemAtIndex;
@end
我希望实现委托(delegate)方法的类只实现一个委托(delegate)方法,而不是同时实现两个委托(delegate)方法。如果委托(delegate)实现了 titleForItemAtIndex
,则它必须不实现imageForItemAtIndex
,反之亦然。如果这两种方法都由委托(delegate)类实现,编译器必须抛出警告(或以其他方式与程序员沟通)。这可能吗?
最佳答案
您可以询问委托(delegate)实例是否响应特定选择器:
if ([self.delegate respondToSelector:@selector(titleForItemAtIndex)]) {
NSString * title = [title titleForItemAtIndex];
}
else if ([self.delegate respondToSelector:@selector(imageForItemAtIndex)]) {
UIImage * title = [title imageForItemAtIndex];
}
这还需要您在协议(protocol)声明中将委托(delegate)方法标记为 @optional
。在这种情况下,您可以保证第一种方法优先于第二种方法。
您可以再添加一个 else
并在没有调用它们时抛出异常。
关于ios - 使两个协议(protocol)方法互斥(实现一个或另一个,而不是两者),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28471885/