假设我已经为子类UIView
定义了一个协议,如下所示:
@protocol MyCustomViewDelegate <NSObject>
- (NSString*) titleForItemAtIndex;
- (UIImage*) imageForItemAtIndex;
@end
我希望实现委托方法的类仅实现一个,而不是两个委托方法。如果委托实现了
titleForItemAtIndex
,则它一定不能实现imageForItemAtIndex
,反之亦然。如果两种方法都由委托类实现,则编译器必须发出警告(或以其他方式将此信息传达给程序员)。那可能吗? 最佳答案
您可以询问委托实例是否响应特定的选择器:
if ([self.delegate respondToSelector:@selector(titleForItemAtIndex)]) {
NSString * title = [title titleForItemAtIndex];
}
else if ([self.delegate respondToSelector:@selector(imageForItemAtIndex)]) {
UIImage * title = [title imageForItemAtIndex];
}
这也将要求您在协议声明中将委托方法标记为
@optional
。在这种情况下,您可以保证第一种方法优先于第二种方法。您可以再添加一个
else
,如果没有一个被调用,则引发异常。