获取Objective-C类或实例的所有方法

问题描述 投票:38回答:4

在Objective-C中,我可以测试给定的类或实例是否响应某些选择器。但是如何查询类或实例的类的所有方法或属性(例如,所有方法或属性的列表)?

objective-c introspection objective-c-runtime
4个回答
9
投票

您将要使用Objective C运行时方法,请参见此处:https://developer.apple.com/reference/objectivec/objective_c_runtime


42
投票

您可以执行此操作,并且它在https://developer.apple.com/library/mac/documentation/cocoa/Reference/ObjCRuntimeRef/index.html中有很多记录,>

要获取类的所有实例或类方法,可以使用class_copyMethodList并遍历结果。一个例子:

 #import <objc/runtime.h>

/**
 *  Gets a list of all methods on a class (or metaclass)
 *  and dumps some properties of each
 *
 *  @param clz the class or metaclass to investigate
 */
void DumpObjcMethods(Class clz) {

    unsigned int methodCount = 0;
    Method *methods = class_copyMethodList(clz, &methodCount);

    printf("Found %d methods on '%s'\n", methodCount, class_getName(clz));

    for (unsigned int i = 0; i < methodCount; i++) {
        Method method = methods[i];

        printf("\t'%s' has method named '%s' of encoding '%s'\n",
               class_getName(clz),
               sel_getName(method_getName(method)),
               method_getTypeEncoding(method));

        /**
         *  Or do whatever you need here...
         */
    }

    free(methods);
}

您将需要对此方法进行两个单独的调用。一个用于实例方法,另一个用于类方法:

/**
 *  This will dump all the instance methods
 */
DumpObjcMethods(yourClass);

在元类上调用相同将为您提供所有类方法

/**
 *  Calling the same on the metaclass gives you
 *  the class methods
 */
DumpObjcMethods(object_getClass(yourClass) /* Metaclass */);

40
投票

除了Buzzy的答案,出于调试目的,您可以使用-[NSObject _methodDescription]私有方法。


4
投票

这可以通过objc_method_list进行。为了枚举您的方法,您必须事先注册所有方法。

© www.soinside.com 2019 - 2024. All rights reserved.