How to determine the number of parameters / keywords of a selector

I know this can be done by decrypting the selector name returned from sel_getName.

But is there any other more convenient predefined runtime information that I can get?

+4
source share
2 answers

See the docs for NSMethodSignature and the -methodSignatureForSelector: NSObject method.

You can request an object for the method signature of any selector that it implements, and then you can send a -numberOfArguments message to the method signature instance.

+10
source

** 1st decision **

The solution is to mix the Objective-C runtime and NSMethodSignature functions .

First you need to include some headers

 #include <objc/objc.h> #include <objc/objc-class.h> #include <objc/objc-runtime.h> 

Then, wherever you want, starting with your selector, you get a parameter counter (note that each method has two implicit parameters self and _cmd , so you should not consider them to have only parameters):

 SEL sel = @selector(performSelector:onThread:withObject:waitUntilDone:); Method m = class_getInstanceMethod([NSObject class], sel); const char *encoding = method_getTypeEncoding(m); NSMethodSignature *signature = [NSMethodSignature signatureWithObjCTypes:encoding]; int allCount = [signature numberOfArguments]; // The parameter count including the self and the _cmd ones int parameterCount = allCount - 2; // Count only the method parameters 

** Second Solution **

Convert the selector to NSString and count the ":" characters. Not sure if it is reliable.

+4
source

All Articles