在Objective C中,如何通过反射找出方法的返回类型?

时间:2011-09-16 16:09:15

标签: objective-c reflection runtime introspection

@interface Foo : NSObject {
}

- (Bar)bar;

在运行时,给定[Foo类],我们如何找出Foo所有方法的返回类型?

我一直在研究Objective-C运行时API;据我所知,没有办法获得方法或属性的返回类型(即Class)。这似乎是任何反射API中的一个严重遗漏。

2 个答案:

答案 0 :(得分:10)

您可以使用Objective-C运行时函数:

Method class_getClassMethod(Class aClass, SEL aSelector)
void method_getReturnType(Method method, char *dst, size_t dst_len)

Objective-C Runtime Reference

首先,使用class_getClassMethod

获取方法对象
Method m = class_getClassMethod( [ SomeClass class ], @selector( someMethod ) );

然后,使用method_getReturnType

请求返回类型
char ret[ 256 ];
method_getReturnType( m, ret, 256 );
NSLog( @"Return type: %s", ret );

答案 1 :(得分:4)