如何在运行时识别方法的返回类型?

时间:2013-11-13 17:10:54

标签: objective-c c cocoa dynamic runtime

为了这个问题,我们假设我有一个Objective-C类,它由以下方法组成:

- (float)method1;
- (CGPoint)method2;
- (NSString *)method3;
- (void)method4;

如何在运行时动态识别上述所有方法的返回类型?

1 个答案:

答案 0 :(得分:3)

您可以使用Objective-C runtime functions获取此信息,但有一些限制。下面的代码将按您的要求执行:

Method method1 = class_getInstanceMethod([MyClass class], @selector(method1));
char * method1ReturnType = method_copyReturnType(method1);
NSLog(@"method1 returns: %s", method1ReturnType);
free(method4ReturnType);

Method method2 = class_getInstanceMethod([MyClass class], @selector(method2));
char * method2ReturnType = method_copyReturnType(method2);
NSLog(@"method2 returns: %s", method2ReturnType);
free(method4ReturnType);

Method method3 = class_getInstanceMethod([MyClass class], @selector(method3));
char * method3ReturnType = method_copyReturnType(method3);
NSLog(@"method3 returns: %s", method3ReturnType);
free(method4ReturnType);

Method method4 = class_getInstanceMethod([MyClass class], @selector(method4));
char * method4ReturnType = method_copyReturnType(method4);
NSLog(@"method4 returns: %s", method4ReturnType);
free(method4ReturnType);

输出:

>>method1 returns: f
>>method2 returns: {CGPoint=dd}
>>method3 returns: @
>>method4 returns: v

method_copyReturnType()返回的字符串是Objective-C类型的编码字符串documented here。请注意,虽然您可以判断方法是否返回一个对象(编码字符串“@”),但您无法分辨它是什么类型的对象。

我很好奇为什么你对此感兴趣。特别是对于一个新的Objective-C程序员,我的第一个倾向是鼓励你思考这是否真的是一个好的设计选择。对于你所问过的方法,这非常简单,但是具有更多异类返回类型的方法可能会导致你使用类型编码的一些棘手的东西。

相关问题