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

接着上一篇文章介绍,这一篇文章我介绍一下,怎么通过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);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,814评论 0 9
  • iOS开发-- Runtime的几个小例子 字数2756阅读1867评论22喜欢88 一、什么是runtime(也...
    K_Gopher阅读 375评论 0 0
  • 参考链接: http://www.cnblogs.com/ioshe/p/5489086.html 简介 Runt...
    乐乐的简书阅读 2,166评论 0 9
  • 对于从事 iOS 开发人员来说,所有的人都会答出【runtime 是运行时】什么情况下用runtime?大部分人能...
    梦夜繁星阅读 3,734评论 7 64
  • 几个觉察 1.我很critical ,所以儿子也是这样。由于职业原因,总是先看到别人的不足,一切都用一种挑剔的眼光...
    海坨的女儿阅读 260评论 0 0