使用method_getReturnType调用特定类型的实例成员函数

问题描述 投票:1回答:1

我是Objective-C的新手,所以我对这门语言并不太了解。

我要做的是遍历对象的所有可用实例方法并调用不带参数的方法,返回bool并以字符串“func”开头。

以下是我获取方法的方法:

uint32_t methodCount = 0;
Method * methods = class_copyMethodList(object_getClass(self), &methodCount);

我遍历这些方法,当上述条件匹配时,尝试调用它们:

NSString * methodName   = [NSString stringWithUTF8String:sel_getName(method_getName(method))];

char retTyp[10];
method_getReturnType(method, retTyp, 10);

const char * desiredRetType = "B";

if([methodName hasPrefix:@"func"] &&
   (0 == strncmp(retTyp, desiredRetType, strlen(desiredRetType))) &&
   (2 == method_getNumberOfArguments(method)))
{
     bool * (* testMethod) (id, Method) = (void (*) (id, Method, ...)) method_invoke;
     result = testMethod(self, method);
}

我必须通过实验弄清楚返回类型字符串是什么(结果是bool的“B”),以及参数的数量。

我在使用method_invoke调用函数的行上遇到以下错误:

cannot initialize a variable of type 'bool *(*)(__strong id, Method)' (aka 'bool *(*)(__strong id, objc_method *)') with an rvalue of type 'void (*)(__strong id, Method, ...)' (aka 'void (*)(__strong id, objc_method *, ...)'): different return type ('bool *' vs 'void') 
  1. 有没有比class_copyMethodList更好的方法来做到这一点?
  2. 如何正确转换函数以避免错误?
  3. 是否有可能返回类型的method_getReturnType()转换可能会在系统之间发生变化?或者它总是B为bool?
objective-c objective-c-runtime
1个回答
0
投票

NVM,我想通了。我没有在方法名称上使用method_invoke,而是这样做:

NSString * methodName   = [NSString stringWithUTF8String:sel_getName(method_getName(method))];

char retTyp[10];

method_getReturnType(method, retTyp, 10);
const char * desiredRetType = "B";

if([methodName hasPrefix:@"func"] &&
   (0 == strncmp(retTyp, desiredRetType, strlen(desiredRetType))) &&
   (2 == method_getNumberOfArguments(method)))
{
    SEL testMethod = method_getName(method);
    return [self performSelector:testMethod];
}
© www.soinside.com 2019 - 2024. All rights reserved.