Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 717
Undistraction Avatar asked Sep 20 '11 22:09

Undistraction


People also ask

How do you pass a method from one method to another?

We can't directly pass the whole method as an argument to another method. Instead, we can call the method from the argument of another method. Here, the returned value from method2 () is assigned as an argument to method1 (). If we need to pass the actual method as an argument, we use the lambda expression.

How do you pass a method as an argument in Java?

Here, the returned value from method2 () is assigned as an argument to method1 (). If we need to pass the actual method as an argument, we use the lambda expression. To learn more, visit Passing Lambda Expression as method argument in Java. In the above example, we have created two methods named square () and add ().

What data types can be passed as arguments to a method?

The basic data types can be passed as arguments to the C# methods in the same way the object can also be passed as an argument to a method. But keep in mind that we cannot pass a class object directly in the method. We can only pass the reference to the object in the method.

What does it mean when a method is passed by reference?

It means that when you call a method, a copy of each argument is passed. You can do whatever you want with that copy inside the method but that will not impact the actual parameter. Though it is always pass-by-value some times it looks like it is passed by reference especially when you pass some object. There are 8 primitive data types in Java.


1 Answers

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:

like image 79
adpalumbo Avatar answered Oct 21 '22 12:10

adpalumbo