2014-05-22 60 views
1

我使用运行时功能向类添加类方法,但是此方法不能被NSInvocation使用。我的代码是这样的:iOS:通过class_addMethod添加的类方法不能被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的原因是因为我想要选择器的返回值,还有其他方法吗?

+0

如果您知道此选择器的签名(其返回类型以及所需的参数类型),则可以手动形成方法签名。 – matt

+0

也可以使用调试器确保您获得整个值。例如,可能'newSelector'为零。 – matt

回答

2

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