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

后端 未结 4 1615
-上瘾入骨i
-上瘾入骨i 2020-12-16 07:39

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 unifi

4条回答
  •  甜味超标
    2020-12-16 07:41

    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
    }
    

提交回复
热议问题