如何为Class方法构建NSInvocation?

sg7*_*sg7 1 objective-c

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

NSMethodSignature *signature;
NSInvocation *inv;

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

Method method = class_getInstanceMethod(targetClass, selector); 
Run Code Online (Sandbox Code Playgroud)

//当我运行代码时,为什么方法为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
Run Code Online (Sandbox Code Playgroud)

由于'方法'总是'无',因此这种方法不起作用.为什么?
通过调用上述代码执行类方法的正确方法是什么?

Lil*_*ard 6

你的代码太复杂了.您可以在NSMethodSignature*不弄乱运行时的情况下获取对象.

signature = [NSString methodSignatureForSelector:@selector(stringWithString:)];
Run Code Online (Sandbox Code Playgroud)