iOS擷取類的屬性列表

來源:互聯網
上載者:User

標籤:屬性列表   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擷取類的屬性列表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.