Pass a protocol as a method argument
First let me explain what I don't mean. I don't want to type an argument to a protocol:
-(void)someMethod:(id<SomeProtocol>)someArgument;
What I do want to is to pass a protocol to a method in the same way I can pass a Class to a method (The following is incorrect, but it hopefully explains what I want to do):
-(void)someMethod:(Protocol)someArgument;
I would then like to be able to use the Protocol to check whether a set of objects implement i开发者_如何学Got.
If you know the name of a protocol at coding-time, use @protocol(SomeProtocol)
to get a pointer to that protocol, similar to how you'd use @selector(x)
.
Beyond that, you just refer to protocols with the class identifier Protocol
-- so you're method declaration would look like:
-(void)someMethod:(Protocol*)someArgument
You can see an example in the docs for NSObject conformsToProtocol:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/clm/NSObject/conformsToProtocol:
Protocol is a class, so you just write - (void)someMethod:(Protocol *)someArgument
like with any other object type. You can see this in the declaration for conformsToProtocol:
:
+ (BOOL)conformsToProtocol:(Protocol *)aProtocol
- (void) executeRequest:(id<Protocol1>)request andCompletion:(id<Protocol2>)response
the only way to pass protocol into an argument
because id<..> means it needs to conform to that protocol before pass throw the argument
I don't recommend using protocol. It will obscure which interface your code actually relies on. Use id<yourprotocol>*
. This is actually how the cocoa frameworks pass protocols. Forgive the use of words if I don't it thinks I'm trying to do HTML.
精彩评论