码迷,mamicode.com
首页 > 移动开发 > 详细

iOS获取类的属性列表

时间:2015-04-28 18:41:17      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:属性列表   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: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.自定义类的序列化和反序列化。


iOS获取类的属性列表

标签:属性列表   class_copypropertyli   

原文地址:http://blog.csdn.net/junjun150013652/article/details/45335469

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!