iOS:由classInadMethod添加的类方法不能由NSInvocation使用

时间:2014-05-22 12:44:02

标签: ios runtime selector class-method nsinvocation

我使用运行时功能将类方法添加到类中,但 NSInvocation 不能使用此方法。我的代码是这样的:

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]];

调用创建语法崩溃为:

*** 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
        ......
)

任何解释?我需要使用 NSInvocation 的原因是因为我想要选择器的返回值,还有其他任何方法吗?

1 个答案:

答案 0 :(得分:2)

您需要将方法的签名字符串作为class_addMethod的第4个参数传递。您正在通过NULL