IPHONE 获得类名或 属性列

来源:互联网 发布:linux ntp客户端配置 编辑:程序博客网 时间:2024/06/04 18:38

属性类型和相关函数

属性(Property)类型定义了对描述属性的结构体objc_property的不透明的句柄。

typedef struct objc_property *Property;

您可以使用函数class_copyPropertyListprotocol_copyPropertyList来获得类(包括范畴类)或者协议类中的属性列表:

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

例如,有如下的类声明:

@interface Lender : NSObject {
    float alone;
}
@property float alone;
@end

您可以象这样获得它的属性:

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

您还可以通过property_getName函数获得属性的名字:

const char *property_getName(objc_property_t property)

函数class_getPropertyprotocol_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_getAttributes函数可以获得属性的名字和@encode编码。关于类型编码的更多细节,参考“类型编码“一节;关于属性的类型编码,见“属性类型编码”“属性特征的描述范例”

const char *property_getAttributes(objc_property_t property)

综合起来,您可以通过下面的代码得到一个类中所有的属性。

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

原创粉丝点击