How to determine if @selector wants a parameter?

The script appears where I have an object that stores an external @selector for later use. By design, I would like to be able to add two kinds of selectors. Simple, without parameters, for example [object add:@selector(doSomething)] , and more complex, with one parameter, for example [object add:@selector(doSomething:)] (colon mind). Let's say the selector is stored in the SEL mySelector variable SEL mySelector .

On execution, I need to choose between [anotherObject performSelector:mySelector] or [anotherObject performSelector:mySelector withObject:userInfo]] .

The way I implemented this solution is to provide a BOOL flag that preserves excessively whether the performance should work with or without an additional parameter. However, although I cannot find this in the documents, I get the feeling that I can also set the selector something like -(BOOL)needsParameter . I know, for example, that UIGestureRecognizer addTarget: action: somehow makes this difference automatically.

Can someone point me in the right direction?

+4
source share
1 answer

You can use the NSMethodSignature class for this. For instance,

 SEL mySelector = …; NSMethodSignature *msig = [anotherObject methodSignatureForSelector:mySelector]; if (msig != nil) { NSUInteger nargs = [msig numberOfArguments]; if (nargs == 2) { // 0 non-hidden arguments } else if (nargs == 3) { // 1 non-hidden argument } else { } } 

Alternatively, you can use NSStringFromSelector() to get the string representation of mySelector and count the number of occurrences of the colon character.

+9
source

Source: https://habr.com/ru/post/1336675/


All Articles