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.