簡體   English   中英

如何為Class方法構建NSInvocation?

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

我想為類方法和選擇器使用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

由於“方法”始終為“零”,因此該方法無效。 為什么?
通過上述代碼的調用執行類方法的正確方法是什么?

您的代碼太復雜了。 您可以獲取NSMethodSignature*對象,而不會弄亂運行時。

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

stringWithString:是一個類方法,您的代碼正在使用class_getInstanceMethod()

嘗試將class_getInstanceMethod()更改為class_getClassMethod()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM