ios 利用runtime打印类的所有属性

来源:互联网 发布:人工智能有关英语作文 编辑:程序博客网 时间:2024/05/29 17:19

1. 你可以用下面这段代码打印一个类的属性列表:

id tfClass = objc_getClass("userClass");unsigned int outCount, i;objc_property_t *properties = class_copyPropertyList(tfClass, &outCount);for (i = 0; i < outCount; i++) {    objc_property_t property = properties[i];    fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));}

2. 属性类型字符串说明

你可以使用 property_getAttributes 方法来获取属性的名字、@encode类型字符串,以及属性的其他属性。

字符串以T开头,然后是 @encode 类型和逗号,最后是V和实例变量的名字。在这之中,属性由以下这些描述符指定:


你可以用 property_getAttributes 方法获取属性的名字和 @encode 类型的字符串。关于编码类型字符串的细节,请参考 《类型编码》章节,细节请参考 《属性类型字符串》和《属性类型描述举例》。

const char *property_getAttributes(objc_property_t property)1

你可以用方法 class_getProperty 和 protocol_getProperty 获取一个类或协议的指定名字的属性的引用:

objc_property_t class_getProperty(Class cls, const char *name)objc_property_t protocol_getProperty(Protocol *proto, const char *name, BOOL isRequiredProperty, BOOL isInstanceProperty)

你可以使用 property_getName 来获取属性名:

const char *property_getName(objc_property_t property)

你可以这样获取属性列表:

id LenderClass = objc_getClass("Lender");unsigned int outCount;objc_property_t *properties = class_copyPropertyList(LenderClass, &outCount);

你可以使用 class_copyPropertyList 和 protocol_copyPropertyList 方法获取一个类、类别或者协议的属性列表:

objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)objc_property_t *protocol_copyPropertyList(Protocol *proto, unsigned int *outCount)

属性声明

当编译器遇到属性声明(参见《The Objective-C Programming Language》中的属性声明),它会为这个类、类别或者协议产生一些描述性的 metadata。你可以通过一些方法访问这些metadata,这些方法能够通过类或者协议的名字查询属性,获取属性的类型,以及拷贝属性的属性。属性声明的列表对每个类和协议都适用。

属性类型和方法

Property 结构定义了属性描述符的handle。

typedef struct objc_property *Property;


0 0