標籤:屬性列表 class_copypropertyli
通過執行個體講解:
@interface DemoObject : NSObject@property (strong, nonatomic,readonly) NSString *name;@property (strong, nonatomic) NSMutableArray *dataSource;@property (copy, nonatomic) NSDictionary *product;@property (assign, atomic) NSUInteger count;@property (weak, nonatomic) DemoObject *object;@end
unsigned int count; objc_property_t *properties = class_copyPropertyList([DemoObject class], &count); for(int i = 0; i < count; i++) { objc_property_t property = properties[i]; NSLog(@"name:%s",property_getName(property)); NSLog(@"attributes:%s",property_getAttributes(property)); } free(properties);
列印資訊如下:
2015-04-28 14:59:16.421 AppTest[11137:94568] name:name
2015-04-28 14:59:16.422 AppTest[11137:94568] attributes:[email protected]"NSString",R,N,V_name
2015-04-28 14:59:16.422 AppTest[11137:94568] name:dataSource
2015-04-28 14:59:16.422 AppTest[11137:94568] attributes:[email protected]"NSMutableArray",&,N,V_dataSource
2015-04-28 14:59:16.422 AppTest[11137:94568] name:product
2015-04-28 14:59:16.422 AppTest[11137:94568] attributes:[email protected]"NSDictionary",C,N,V_product
2015-04-28 14:59:16.422 AppTest[11137:94568] name:count
2015-04-28 14:59:16.422 AppTest[11137:94568] attributes:TQ,V_count
2015-04-28 14:59:16.422 AppTest[11137:94568] name:object
2015-04-28 14:59:16.422 AppTest[11137:94568] attributes:[email protected]"DemoObject",W,N,V_object
說明:
如果我們要擷取字串,要通過UTF8編碼擷取,如下所示:
NSString *name = [NSString stringWithUTF8String:property_getName(property)];NSString *attributes = [NSString stringWithUTF8String:property_getAttributes(property)];
屬性的特性是固定格式,以逗號隔開,通常是[email protected]"類型"開頭,V_屬性名稱結尾的格式,中間的見下表描述:
You can use the property_getAttributes function to discover the name, the @encode type string of a property, and other attributes of the property.
The string starts with a T followed by the @encode type and a comma, and finishes with a V followed by the name of the backing instance variable. Between these, the attributes are specified by the following descriptors, separated by commas:
還有一些其他類型的屬性執行個體,可以搜尋蘋果文檔“Property Attribute Description Examples”
用途:
1.我們在發送網路請求的時候,收到伺服器回複的資料模型以後,不需要在每個資料模型裡面去解析json字典為我們的模型類,我們可以通過一個基類來實現這個功能,所有的模型都繼承這個基類就OK了,這個功能就可以簡單地通過屬性列表來擷取屬性名稱,屬性類型(屬性類型對應json模型的鍵)然後賦值就可以了。
2.自訂類的序列化和還原序列化。
iOS擷取類的屬性列表