美文网首页程序员
OC通过runtime反射获取所有实例方法和类对象方法(静态方法

OC通过runtime反射获取所有实例方法和类对象方法(静态方法

作者: 何景根 | 来源:发表于2020-11-19 17:26 被阅读0次

    本文主要阐述Objective-C如何通过runtime反射获取方法并调用
    属性和变量的反射遍历可以参考https://www.jianshu.com/p/1a03524d6668

    引入头文件

    #import <objc/runtime.h>
    

    获取类实例方法

    Class currentClass=NSClassFromString(@"DlibClass");
        do{
            unsigned int methodCount;
            
            Method *methodList = class_copyMethodList(currentClass, &methodCount);
            unsigned int i = 0;
            for (; i < methodCount; i++) {
                SEL sel=method_getName(methodList[i]);
                NSString *strClassName=[NSString stringWithCString:class_getName(currentClass) encoding:NSUTF8StringEncoding];
                NSString *strMethodName=[NSString stringWithCString:sel_getName(sel) encoding:NSUTF8StringEncoding];
                NSLog(@"class:%@ method:%@", strClassName,strMethodName);
            }
            
            free(methodList);
            currentClass = class_getSuperclass(currentClass);
            
        }while(currentClass);
    

    获取类方法(静态方法)

        Class currentClass=objc_getMetaClass("DlibClass");
        do{
            unsigned int methodCount;
            
            Method *methodList = class_copyMethodList(currentClass, &methodCount);
            unsigned int i = 0;
            for (; i < methodCount; i++) {
                SEL sel=method_getName(methodList[i]);
                NSString *strClassName=[NSString stringWithCString:class_getName(currentClass) encoding:NSUTF8StringEncoding];
                NSString *strMethodName=[NSString stringWithCString:sel_getName(sel) encoding:NSUTF8StringEncoding];
                NSLog(@"class:%@ method:%@", strClassName,strMethodName);
            }
            
            free(methodList);
            currentClass = class_getSuperclass(currentClass);
        
            
        }while(currentClass);
    

    反射创建类实例

     Class Dcls=NSClassFromString(@"DlibClass");
     id dobj=[[Dcls alloc] init];
    

    反射创建无类实例(也叫类对象)

     Class currentClass=objc_getMetaClass("DlibClass");
     id dclsobj=[[currentClass alloc] init];
    

    根据@selector调用相应对象方法

     IMP imp = [dobj methodForSelector:sel];
    MyClass *(*func)(void) = (void *)imp;
    MyClass *ret=func();
    NSLog(@"%@",ret);
    

    相关文章

      网友评论

        本文标题:OC通过runtime反射获取所有实例方法和类对象方法(静态方法

        本文链接:https://www.haomeiwen.com/subject/zejliktx.html