简体   繁体   中英

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. 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?

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.

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

stringWithString: is a class method, your code is using class_getInstanceMethod() .

Try changing class_getInstanceMethod() to class_getClassMethod() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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