Lorenzo Ang
Lorenzo Ang

Reputation: 1318

Is it possible to pass a selector or a method signature as a parameter in Objective-C?

As my title states, I'm wondering if I can pass a method signature or an @selector as a parameter? I'm asking because I'm creating a framework and I want to be able to pass instances of a certain class within it a method name.

Upvotes: 0

Views: 86

Answers (2)

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81868

Actually, you cannot not pass a selector to a method.

In Objective-C, every method gets two implicit arguments, passed as normal parameters: The instance pointer self and the target selector _cmd. They are present in each and every method. The _cmd parameter is of type SEL. It is used by the runtime to look up the method implementation (this is the core of objc's dynamism).

You can, of course, add additional parameter of SEL type.

Upvotes: 0

nburk
nburk

Reputation: 22731

You can pass the selector itself of use the name of the method as a string:

- (void)myMethod:(SEL)selector
{
   [aClass performSelector:selector];
}

or

NSString *myMethodName = NSStringFromSelector(@selector(myMethod));
NSLog(@"The name of the method is: %@", myMethodName);

Upvotes: 1

Related Questions