【问题标题】:Obtain list of class methods for an arbitrary class获取任意类的类方法列表
【发布时间】:2010-11-19 22:24:39
【问题描述】:

如何获取特定类的 class 方法列表?我试过使用<objc/runtime.h> 中声明的class_copyMethodList 函数,但这只是给了我实例方法。我还找到了一个函数,它为我提供了一个类方法的 Method,但前提是我首先拥有该方法的选择器 (class_getClassMethod)。

有什么想法吗?

谢谢,

戴夫

【问题讨论】:

    标签: objective-c cocoa objective-c-runtime


    【解决方案1】:

    class_copyMethodList 返回传递的类的实例方法。类方法实际上是类元类的实例方法。

    您的问题的解决方案包含在API Documentation for class_copyMethodList 中。

    【讨论】:

      【解决方案2】:

      使用元类。

      #import <objc/runtime.h>
      
      int unsigned numMethods;
      Method *methods = class_copyMethodList(objc_getMetaClass("NSArray"), &numMethods);
      for (int i = 0; i < numMethods; i++) {
          NSLog(@"%@", NSStringFromSelector(method_getName(methods[i])));
      }
      free(methods);
      

      【讨论】:

      • 因为这是copy 方法,完成后不要忘记free(methods)。无论您是否使用 ARC — C 分配都不会被引用计数,因此自动引用计数不会帮助您。
      • 文档在导入路径上好像有点模糊,我用的是:#import
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 2012-04-26
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      相关资源
      最近更新 更多