获取类的方法名字

//
//  main.m
//  PrintMethodNamesOfClass
//
//  Created by jqrios on 2021/7/22.
//

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

void printMethodNamesOfClass(Class cls) {
    unsigned int count;
    // 获得方法数组
    Method *methodList = class_copyMethodList(cls, &count);
    
    // 存储方法名
    NSMutableString *methodNames = [NSMutableString string];
    
    // 遍历所有的方法
    for (int i = 0; i < count; i++) {
        // 获得方法
        Method method = methodList[i];
        // 获得方法名
        NSString *methodName = NSStringFromSelector(method_getName(method));
        // 拼接方法名
        [methodNames appendString:methodName];
        [methodNames appendString:@", "];
    }
    
    // 释放
    free(methodList);
    
    // 打印方法名
    NSLog(@"%@ %@", cls, methodNames);
}


@interface Person : NSObject
@end

@implementation Person

/// 类方法
+ (void)test0ClassFunction { }
+ (void)test1ClassFunction { }
/// 实例方法
- (void)test0InstanceFunction { }
- (void)test1InstanceFunction { }

@end


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        printMethodNamesOfClass(object_getClass([Person class]));
        printMethodNamesOfClass(object_getClass([[Person alloc] init]));
    }
    return 0;
}

打印结果

2021-07-22 19:34:14.362188+0800 PrintMethodNamesOfClass[42222:5422215] Person test0ClassFunction, test1ClassFunction,
2021-07-22 19:34:14.362506+0800 PrintMethodNamesOfClass[42222:5422215] Person test0InstanceFunction, test1InstanceFunction,
Program ended with exit code: 0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。