Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

objective-c

I know it can be done by decoding the selector name returned from sel_getName.

But is there any other more convenient preloaded info in runtime that I can get?

like image 980
an0 Avatar asked Dec 10 '22 18:12

an0


2 Answers

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

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

like image 151
NSResponder Avatar answered May 13 '23 15:05

NSResponder


** 1st Solution **

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

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 the parameter's count (note that every method has two implicit parameters self and _cmd, so you have to not count them to have only the 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's parameters

** 2nd Solution **

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

like image 44
Laurent Etiemble Avatar answered May 13 '23 14:05

Laurent Etiemble