声明委托人遵守其他协议 [英] Declare that delegate conforms to another protocol
问题描述
在Objective-C中,是否可以在第二个委托协议定义中包括与委托协议的一致性?我正在尝试避免这样的模式:
In Objective-C, is it possible to include conformance to a delegate protocol inside a second delegate protocol definition? I'm trying to avoid a pattern like this:
if ([objectA conformsToProtocol:@protocol(privateDelegateProtocol)])
{
id<privateDelegateProtocol> privateDelegate = (id<privateDelegateProtocol>)objectA;
objectB.privateDelegate = privateDelegate;
}
我已经知道 objectA
符合我自己的委托协议 @protocol(myDelegateProtocol)
,因为实际上 self.myDelegate = objectA
。如果我可以在该协议定义中以某种方式指定它还必须符合 @protocol(privateDelegateProtocol)
,那么我可以这样写:
I already know that objectA
conforms to my own delegate protocol @protocol(myDelegateProtocol)
, because in fact self.myDelegate = objectA
. If I could somehow specify in that protocol definition that it must also conform to @protocol(privateDelegateProtocol)
, then I could just write:
objectB.privateDelegate = self.myDelegate;
这似乎更简单,更优雅。如果协议方法未实现,我宁愿收到编译时警告,而不必在运行时进行检查。有办法吗?
which seems much simpler and more elegant. I'd much rather get a compile time warning if the protocol methods are not implemented, rather than have to check for that at runtime. Is there a way?
推荐答案
协议可以像类一样从协议继承。
Protocols can inherit from protocols the same way classes do.
@protocol myDelegateProtocol <NSObject, privateDelegateProtocol>
...
@end
任何符合该协议的对象都必须还符合NSObject和privateDelegateProtocol协议。
Any object that conforms to that protocol must also conform to the NSObject and privateDelegateProtocol protocols.
您还可以指定您的委托人必须同时遵守这两个协议,而不要求所有符合myDelegateProtocol的对象也必须遵守privateDelegateProtocol。
You can also specify that your delegate must conform to both protocols without requiring all objects that conform to myDelegateProtocol also conform to privateDelegateProtocol.
@property (nonatomic, weak) id<myDelegateProtocol, privateDelegateProtocol> delegate;
这篇关于声明委托人遵守其他协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!