繁体   English   中英

如何为Class方法构建NSInvocation?

[英]How can I build NSInvocation for the Class method?

我想为类方法和选择器使用NSClassFromString和NSSelectorFromString构建调用。 我尝试通过以下方式构建调用:

NSMethodSignature *signature;
NSInvocation *inv;

Class targetClass = NSClassFromString(@"NSString");
SEL selector   = NSSelectorFromString(@"stringWithString:");
id arg = @"argument";

Method method = class_getInstanceMethod(targetClass, selector); 

//为什么我运行代码时方法为nil?

struct objc_method_description* desc = method_getDescription(method);

if (desc == NULL || desc->name == NULL){
    return nil;
}

signature = [NSMethodSignature signatureWithObjCTypes:desc->types];
inv = [NSInvocation invocationWithMethodSignature:signature];
[inv setSelector:selector];
[inv setArgument:&arg atIndex:2];
[inv invoke];

__autoreleasing id returnObj;    
[inv getReturnValue:&returnObj];    // get created object

由于“方法”始终为“零”,因此该方法无效。 为什么?
通过上述代码的调用执行类方法的正确方法是什么?

您的代码太复杂了。 您可以获取NSMethodSignature*对象,而不会弄乱运行时。

signature = [NSString methodSignatureForSelector:@selector(stringWithString:)];

stringWithString:是一个类方法,您的代码正在使用class_getInstanceMethod()

尝试将class_getInstanceMethod()更改为class_getClassMethod()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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