你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS獲取類的屬性列表

iOS獲取類的屬性列表

編輯:IOS開發綜合

通過實例講解

 

@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:T@"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:T@"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:T@"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:T@"DemoObject",W,N,V_object

 

說明:

如果我們要獲取字符串,要通過UTF8編碼獲取,如下所示:

 

NSString *name = [NSString stringWithUTF8String:property_getName(property)];
NSString *attributes = [NSString stringWithUTF8String:property_getAttributes(property)];

 

屬性的特性是固定格式,以逗號隔開,通常是T@"類型"開頭,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.自定義類的序列化和反序列化。

 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved