简体   繁体   English

如何为Class方法构建NSInvocation?

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

I would like to build the invocation using NSClassFromString and NSSelectorFromString for the class method and the selector. 我想为类方法和选择器使用NSClassFromString和NSSelectorFromString构建调用。 I tried to build invocation in the following way: 我尝试通过以下方式构建调用:

NSMethodSignature *signature;
NSInvocation *inv;

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

Method method = class_getInstanceMethod(targetClass, selector); 

// why is the method nil when I run the code? //为什么我运行代码时方法为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

Since 'method' is always 'nil' this approach does not work. 由于“方法”始终为“零”,因此该方法无效。 Why? 为什么?
What is the proper way to execute class method via invocation for the above code? 通过上述代码的调用执行类方法的正确方法是什么?

Your code is too complicated. 您的代码太复杂了。 You can get an NSMethodSignature* object without messing around with the runtime. 您可以获取NSMethodSignature*对象,而不会弄乱运行时。

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

stringWithString: is a class method, your code is using class_getInstanceMethod() . stringWithString:是一个类方法,您的代码正在使用class_getInstanceMethod()

Try changing class_getInstanceMethod() to class_getClassMethod() . 尝试将class_getInstanceMethod()更改为class_getClassMethod()

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

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