使用runtime获取成员变量

来源:互联网 发布:a站和b站区别知乎 编辑:程序博客网 时间:2024/06/04 18:56


使用runtime的时候我们必须包含头文件#import<objc/runtime.h>。runtime 可以用来获取一个类的全部成员变量,有时我们开发时会用到一些属性,而我们直接又是访问不到的,这时runtime就有用了。

获取成员变量有两种方法:

通过 class_copyPropertyList 获取的成员变量仅仅是对象类的属性(@property声明的属性

  unsigned int count = 0;        objc_property_t *properties = class_copyPropertyList([UITextField class], &count);            for (int i = 0; i<count; i++) {            objc_property_t property = properties[i];            NSLog(@"%s",property_getName(property));        }            free(properties);


还有一种是通过copyIvarList 获取,这种方法获取的是所有属性和变量(包括在@interface大括号中声明的变量)

 unsigned int count = 0;    Ivar *ivars = class_copyIvarList([UITextField class], &count);        for (int i = 0; i<count; i++) {        Ivar property = ivars[i];        NSLog(@"%s---%@",ivar_getName(property),[NSString stringWithUTF8String:ivar_getName(property)]);    }        free(ivars);




0 0
原创粉丝点击