Declare that delegate conforms to another protocol

2019-09-07 06:47发布

问题:

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;
    }

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?

回答1:

Protocols can inherit from protocols the same way classes do.

@protocol myDelegateProtocol <NSObject, privateDelegateProtocol>
...
@end

Any object that conforms to that protocol must also conform to the NSObject and privateDelegateProtocol protocols.

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;