【问题标题】:How do I identify the return type of a method during runtime? [closed]如何在运行时识别方法的返回类型? [关闭]
【发布时间】:2013-11-13 17:10:53
【问题描述】:

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

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

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

【问题讨论】:

  • 建议在发帖寻求帮助之前先完成一些基本的 Objective C 教程
  • 我认为stackoverflow.com/questions/4229777/… 回答了你的问题
  • @bengoesboom,该问题只有收件人对象返回(您无法区分)。可以使用method_getReturnType() 获取有关原始返回类型的信息。一个更好的讨论在这里:stackoverflow.com/questions/7447559/…
  • 也就是说,作为菜鸟,您不太可能希望在实际程序中执行此操作。这种自省是一个非常高级的话题。研究它并了解有关运行时的更多信息是很好的(你不应该害怕运行时),但除非你正在构建像测试工具这样的元框架,否则你不太可能这样做。

标签: objective-c c cocoa dynamic runtime


【解决方案1】:

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

【讨论】:

  • 没问题,玩运行时总是很有趣。
猜你喜欢
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多