當(dāng)編譯器遇到變量聲明時(shí),將結(jié)合類、類別或者協(xié)議生成描述性元數(shù)據(jù),你可以通過根據(jù)屬性名稱獲取類的或者協(xié)議的屬性的函數(shù)得到一個(gè)屬性用@encode字符串表示的類型,并且將屬性的特性復(fù)制出來用C字符串的數(shù)組表示。任何一個(gè)類或者協(xié)議都有聲明屬性的數(shù)組
Property Type and Functions
Property結(jié)構(gòu)體定義對(duì)屬性的描述不透明
typedef struct objc_property *Property;
你可以通過函數(shù) class_copyPropertyList 和 protocol_copyPropertyList來分別獲得關(guān)聯(lián)類(包括已經(jīng)加載的類別)和協(xié)議的屬性列表
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);
同時(shí)可以用property_getName函數(shù)獲取屬性名稱
const char *property_getName(objc_property_t property)
可以用 class_getProperty 和 protocol_getProperty 根據(jù)屬性名稱分別獲取類或者協(xié)議里面的屬性引用(reference)
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 函數(shù)來找到屬性的名稱和用@encode字符串表示的類型。詳情見下面Property Type String章節(jié)。
const char *property_getAttributes(objc_property_t property)
結(jié)合上面的幾種函數(shù)。你可以打印一個(gè)類的所有屬性,如下:
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));
}
Property Type String
你可以通過property_getAttributes函數(shù)來找到屬性的名稱和@encode類型字符串,以及其他屬性的特性
屬性類型字符串以字母T開頭,緊接著是@encode類型和一個(gè)逗號(hào),最后以V加返回實(shí)例的名稱結(jié)尾。在這中間,屬性的特性由下面幾種描述符表示,用逗號(hào)分開:

詳細(xì)見下方例子
Property Attribute Description Examples
列舉下面幾種定義:
enum FooManChu { FOO, MAN, CHU };
struct YorkshireTeaStruct { int pot; char lady; };
typedef struct YorkshireTeaStruct YorkshireTeaStructType;
union MoneyUnion { float alone; double down; };
下表展示了例子屬性聲明對(duì)應(yīng)著的property_getAttributes:函數(shù)返回

