Undistraction
Undistraction

Reputation: 43589

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 it.

Upvotes: 17

Views: 14482

Answers (4)

Chea Sambath
Chea Sambath

Reputation: 1335

- (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

Upvotes: 3

Solomon
Solomon

Reputation: 39

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.

Upvotes: 1

adpalumbo
adpalumbo

Reputation: 3031

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:

Upvotes: 17

Chuck
Chuck

Reputation: 237010

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

Upvotes: 3

Related Questions