论坛首页 移动开发技术论坛

属性类型和相关函数

浏览 3107 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-01-15  
iOS
属性(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;
    fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));
}
   发表时间:2010-01-18  
long4 兄
这篇文章看起比 cocoachina 上的丰满不少哈。
0 请登录后投票
论坛首页 移动开发技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics