属性类型和相关函数
属性
(Property)类型定义了对描述属性的结构体objc_property
的不透明的句柄。
typedef struct objc_property *Property; |
您可以使用函数class_copyPropertyList
和protocol_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_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_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)); |
} |