我想为类方法和选择器使用 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
由于“方法”总是“零”,这种方法不起作用。为什么?
通过调用上述代码执行类方法的正确方法是什么?