获取类的方法名字

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

#import 
#import 

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

你可能感兴趣的:(获取类的方法名字)