Search code examples
iphonensinvocation

How to use NSInvocation to call a class method?


I've a class method which is not declared in the h file, but implemented in the m file. now I want to call it in another class, since the return value is a int, I can't use selector directly, so I use NSInvocation.

below is what i'm doing:

SEL selector = ***;
NSMethodSignature *signature = [classA methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation.selector = selector;
invocation.target = [classA class];
[invocation setArgument:(void *)arg atIndex:2];
[invocation invoke];

the invoke doesn't succeed, Why?


Solution

  • When passing the arguments, you pass their address, not their value. Try the following:

    [invocation setArgument:&arg
                    atIndex:2];
    

    See [NSInvocation setArgument:atIndex:] in the class reference.