简体   繁体   中英

iOS: Class method added by class_addMethod can't be used by NSInvocation

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM