开发者

How to determine whether a @selector wants a parameter?

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

In the execution, I need to decide between [anotherObject performSelector:mySelector] or [anotherObject performSelector:mySelector withObject:userInfo]].

The way I implemented this decision, is by providing a BOOL flag that redundantly stores whether the performance should be with or without the extra parameter. Yet although I can't find this in the docs, I have the feeling that I should also be able to ask the selector something like -(BOOL)needsParameter. I know, for example, that UIGestureRecognizer's addTarget:action: somehow makes this distinction automatically.

Could someone point me in the right dir开发者_开发百科ection?


You can use the NSMethodSignature class for that. 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 could use NSStringFromSelector() to get the string representation of mySelector and count the number of occurrences of the colon character.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜