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

标签 objective-c c cocoa dynamic runtime

对于这个问题,假设我有一个由以下方法组成的 Objective-C 类:

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

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

最佳答案

您可以使用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 程序员,我的第一个倾向是鼓励你思考这是否真的是一个好的设计选择。对于您询问的方法,这非常简单,但是具有更奇特的返回类型的方法可能会导致您遇到一些类型编码更棘手的问题。

关于objective-c - 如何在运行时识别方法的返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19960072/

相关文章:

objective-c - NSDecimalNumber 乘法奇怪

c++ - MPI、C、派生类型、 vector 结构?

macos - 使用 NSWindow 还是 NSViewController?

macos - 在 Interface Builder MacO 中从 localized.strings 获取字符串

objective-c - 如何在 OS X 应用程序中应用 shell 扩展(图标覆盖)和上下文菜单?

ios - Swift - 离屏渲染

ios - 从 WKWebview 检索 HTTP 响应 header

c - 绝对值计算

c - 使用动态字符串从 C 中的字符串中删除一个字符

ios - 如何向 UILabel 的固有内容大小添加填充?