Runtime(三)获取关于一个类的所有内容

2017-07-31  本文已影响0人  为什么划船不靠桨
接着上一篇文章介绍,这一篇文章我介绍一下,怎么通过Runtime获取我们想获取到一个类的一切内容,哪怕是系统类.那么在控制器中,我们到底怎么才能获取到Person类的一切内容呢?耐心往下看0
首先别忘了导入头文件<objc/runtime.h>,然后进行如下操作~~~

一、在ViewController中通过对象获取类名字

//通过对象获取类名字
const char *name = class_getName(per.class);

二、获取属性列表

    unsigned int count = 0;
    //获得指向该类所有属性的指针
    objc_property_t *pro = class_copyPropertyList(per.class, &count);
    //遍历属性
    for (unsigned int i = 0; i < count; i++) {
       const char *objcName = property_getName(pro[i]);
        NSLog(@"第%d个属性为%s",i,objcName);
        //将C的字符串转为OC的
        //NSString *key = [NSString stringWithUTF8String:name];
  }
    //记得释放
    free(pro);

三、获取成员变量列表(更全面)

unsigned int _count;
    //  Ivar:表示成员变量类型
    // & 代表获得一个指向该类成员变量的指针
    Ivar * ivars = class_copyIvarList(per.class,&_count);
    
    for (int i = 0 ; i<_count; i++) {
        // 根据ivar获得其成员变量的名称--->C语言的字符串
        const char * name = ivar_getName(ivars[i]);
        //也可以转为OC的字符串
        //NSString *key = [NSString stringWithUTF8String:name];
        NSLog(@"实例变量%s",name);
        //获取属性类型
        const char *namerType = ivar_getTypeEncoding(ivars[i]);
        //对私有变量进行修改
        object_setIvar(per, ivars[0], @"上海");
    }
  //记得释放
    free(ivars);

四、获取一个类的全部方法

unsigned int countMethod;
    //获取指向该类所有方法的指针
    Method * methods = class_copyMethodList(per.class, &countMethod);
    
    for (int i = 0 ; i < countMethod; i++) {
        //获取该类的一个方法的指针
        Method method = methods[i];
        //获取方法
        SEL methodSEL = method_getName(method);
        //将方法转换为C字符串
        const char *name = sel_getName(methodSEL);
        NSLog(@"方法%s",name);
        //将C字符串转为OC字符串
        NSString *methodName = [NSString stringWithUTF8String:name];
        //获取方法参数个数
        int arguments = method_getNumberOfArguments(method);
        NSLog(@"%d == %@ %d",i,methodName,arguments);
  }
  //记得释放
    free(methods);

五、获取一个类遵循的全部协议

unsigned int count;

    //获取指向该类遵循的所有协议的指针
    __unsafe_unretained Protocol **protocols = class_copyProtocolList([self class], &count);

    for (int i = 0; i < count; i++) {
        //获取该类遵循的一个协议指针
        Protocol *protocol = protocols[i];
        //获取C字符串协议名
        const char *name = protocol_getName(protocol);
        //C字符串转OC字符串
        NSString *protocolName = [NSString stringWithUTF8String:name];
        NSLog(@"%d == %@",i,protocolName);
    }
    //记得释放
    free(protocols);
上一篇 下一篇

猜你喜欢

热点阅读