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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值