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.自定义类的序列化和反序列化。


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。