Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

objective c - Calling a selector with unknown number of arguments using reflection / introspection

Lately I wrote an application in java (for android) which used reflection to invoke methods of some objects. The argument number and type was unknown, meaning, I had a unified mechanism that received an object name, method name and array of parameters (using JSON) and invoked the specified method on the specified object with an array of the arguments (Object[] filled with arguments of the required types).

Now I need to implement the same for iOS, I was able to invoke a selector when I knew the number of parameters the selector expected for like this:

SEL selector = NSSelectorFromString(@"FooWithOneArg");
[view performSelectorInBackground:selector withObject:someArg];

I know I can get the number of arguments the selector receives by using

int numberOfArguments = method_getNumberOfArguments(selector);

But is there a way to make a generic call like this:

[someObject performSelector:selector withObject:arrayOfObjects]

which is pretty much equivalent to Java's

someMethod.invoke(someObject, argumentsArray[]);

?

I want to avoid a switch case according to the amount of arguments the selector gets.

Sorry for the long dig, I just want to make my question as clear as possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This small function should do the trick, its not perfect, but it gives you a starting point:

void invokeSelector(id object, SEL selector, NSArray *arguments)
{
    Method method = class_getInstanceMethod([object class], selector);
    int argumentCount = method_getNumberOfArguments(method);

    if(argumentCount > [arguments count])
        return; // Not enough arguments in the array

    NSMethodSignature *signature = [object methodSignatureForSelector:selector];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    [invocation setTarget:object];
    [invocation setSelector:selector];

    for(int i=0; i<[arguments count]; i++)
    {
        id arg = [arguments objectAtIndex:i];
        [invocation setArgument:&arg atIndex:i+2]; // The first two arguments are the hidden arguments self and _cmd
    }

    [invocation invoke]; // Invoke the selector
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...