Pass a protocol as a method argument
Solution 1
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:
Solution 2
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
Solution 3
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.
Solution 4
- (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
Undistraction
Updated on June 03, 2022Comments
-
Undistraction about 2 years
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 it.
-
Undistraction almost 13 yearsThanks. So out of interest why does Protocol use a pointer while Class doesn't?
-
adpalumbo almost 13 yearsI'm afraid I don't have answer to that, myself. Good question, though.
-
jscs almost 13 yearsProtocols and classes are each represented by their own classes. The difference is, the word
Class
is defined as being a pointer, butProtocol
is just the name of the class, like any other (NSString
, e.g.); so for aProtocol
instance you must have an explicit pointer. @1nd -
Chuck almost 13 years@1ndivisible: Protocol is a class, just like NSString or NSArray.
Class
is not a class, it's a type that signifies a pointer to a class, much the same asid
signifies a pointer to objects. -
Solomon about 12 yearsAlso this is a strongly typed language so don't try and make it act loosely typed
-
Millie Smith almost 10 yearsIs this down voted because it's not what OP wants? This is what I want...
@protocol(MyProtocol)varname
didn't even compile for me. -
vishal dharankar about 3 yearsperfect , this something others not mentioning