ObjCRuntimeGuide小记(3)

比如,void编码为v,char编码为c,对象编码为@,类编码为#,选择符编码为:,而符合类型则由基本类型组成,比如

typedef struct example {        id     anObject;        char *aString;        int anInt;   } Example;  

编码为{example=@*i}。

属性声明

当编译器遇到属性声明时,它会生成一些可描述的元数据(metadata),将其与相应的类、category和协议关联起来。存在一些函数可以通过名称在类或者协议中查找这些metadata,通过这些函数,我们可以获得编码后的属性类型(字符串),复制属性的attribute列表(C字符串数组)。因此,每个类和协议的属性列表我们都可以获得。

与类型编码类似,属性类型也有相应的编码方案,比如readonly编码为R,copy编码为C,retain编码为&等。

通过property_getAttributes函数可以后去编码后的字符串,该字符串以T开头,紧接@encode type和逗号,接着以V和变量名结尾。比如:

@property char charDefault;

描述为:Tc,VcharDefault

而@property(retain)ididRetain;

描述为:T@,&,VidRetain

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)  

通过property_getName函数可以获取属性名称。

通过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 type string:

const char *property_getAttributes(objc_property_t property)

以上函数组合成一段示例代码:

@interface Lender : NSObject {        float alone;   }   @property float alone;   @end      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));   }  

END。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyzygj.html