How to get the arity of a method?

寵の児 提交于 2019-12-13 18:20:01

问题


In Javascript, for example, you can get the arity (the number of arguments a function is supposed to take) by simply func.length. How can I get this information for a method in Objective-C?


回答1:


NSMethodSignature is awesome for all kind of reflection information.

SEL selector = @selector(foo:);
NSMethodSignature *sig = [someObj methodSignatureForSelector:selector]
int argCount = [sig numberOfArguments];



回答2:


When there’s no receiver object to send -methodSignatureForSelector: to, it’s possible to use NSStringFromSelector() and count the number of occurrences of the colon character.




回答3:


From The Objective-C Runtime Reference

method_getNumberOfArguments

Returns the number of arguments accepted by a method.

unsigned method_getNumberOfArguments(Method method) Parameters method A pointer to a Method data structure. Pass the method in question. Return Value An integer containing the number of arguments accepted by the given method.



来源:https://stackoverflow.com/questions/3571739/how-to-get-the-arity-of-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!