1

I add a class method to a class using runtime feature, but this method can't be used by NSInvocation. My code is as this:

id metaClass = object_getClass((id)protocolClass);
IMP prevImp = class_replaceMethod(metaClass, @selector(xxx), imp, NULL);

const char *selectorName = sel_getName(@selector(xxx));
char newSelectorName[strlen(selectorName) + 10];
strcpy(newSelectorName, "ORIGIN");
strcat(newSelectorName, selectorName);
SEL newSelector = sel_getUid(newSelectorName);
if(!class_respondsToSelector(metaClass, newSelector)) {
    class_addMethod(metaClass, newSelector, prevImp, NULL);
}

NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
                            [protocolClass methodSignatureForSelector:newSelector]];

The invocation creating syntax crash as:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSMethodSignature signatureWithObjCTypes:]: type signature is empty.'
*** First throw call stack:
(
    0   CoreFoundation                      0x07c251e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x079a48e5 objc_exception_throw + 44
    2   CoreFoundation                      0x07c13ce4 +[NSMethodSignature signatureWithObjCTypes:] + 1172
    3   CoreFoundation                      0x07cc22e9 +[NSObject(NSObject) methodSignatureForSelector:] + 73
        ......
)

Any explanation? The reason I need to use NSInvocation is because I want the return value of the selector, any other methods?

Cœur
  • 37,241
  • 25
  • 195
  • 267
keywind
  • 1,135
  • 14
  • 24
  • If you know the signature of this selector (its return type and what kind of parameters it takes), you can form the method signature manually. – matt May 22 '14 at 14:55
  • Also use the debugger to make sure you're getting values throughout. Maybe `newSelector` is nil, for example. – matt May 22 '14 at 14:58

1 Answers1

2

You need to pass the signature string of the method as the 4th argument of class_addMethod. You are passing NULL.

newacct
  • 119,665
  • 29
  • 163
  • 224