iOS runtime 根据类名获取属性的类型和名称

来源:互联网 发布:php referer 编辑:程序博客网 时间:2024/06/08 05:46

最近想简单封装一下FMDB,简单实现根据模型创建表的功能。

又研究了下runtime,解析property_getAttributes即可获得属性类型名称等

@protocol Aprotocol <NSObject>


@end


typedefvoid(^TestBlock)(int age);

@interface Student :NSObject

@property(nonatomic,copy)NSString<Aprotocol> *name ;

@property(nonatomic,assign)int score;

@property(nonatomic,assign)CGFloat cgfloat ;

@property(nonatomic,strong)NSArray *arr;

@property(nonatomic,strong)NSNumber *number;

@property(nonatomic,assign)float   afloat;

@property(nonatomic,weak)id   anId;

@property(          strong)Student *stu;

@property(nonatomic,copy)TestBlock   thisBlock;

@property BOOL aBool;  //TB,V_aBool

@propertychar charDefault;

@property(retain)id idRetain;

@property CGRect rect ;

@end


[selfanilistMyClass:objc_getClass("Student")];


- (void)anilistMyClass:(Class)className{

   u_int count;

   objc_property_t * properties  = class_copyPropertyList(className, &count);

   for (int i=0; i<count; i++) {

       objc_property_t property = properties[i];

       NSLog(@"%@-->%@",getPropertyType(property),getPropertyName(property));

    }

   free(properties);

}


得到如下结果:

2015-09-20 10:22:55.130 RuntimeSample[6589:353450] NSString-->name

2015-09-20 10:22:55.130 RuntimeSample[6589:353450] int-->score

2015-09-20 10:22:55.131 RuntimeSample[6589:353450] double-->cgfloat

2015-09-20 10:22:55.131 RuntimeSample[6589:353450] NSArray-->arr

2015-09-20 10:22:55.131 RuntimeSample[6589:353450] NSNumber-->number

2015-09-20 10:22:55.132 RuntimeSample[6589:353450] float-->afloat

2015-09-20 10:22:55.132 RuntimeSample[6589:353450] id-->anId

2015-09-20 10:22:55.132 RuntimeSample[6589:353450] Student-->stu

2015-09-20 10:22:55.132 RuntimeSample[6589:353450] Block-->thisBlock

2015-09-20 10:22:55.132 RuntimeSample[6589:353450] BOOL-->aBool

2015-09-20 10:22:55.132 RuntimeSample[6589:353450] char-->charDefault

2015-09-20 10:22:55.133 RuntimeSample[6589:353450] id-->idRetain

2015-09-20 10:22:55.133 RuntimeSample[6589:353450] CGRect-->rect



0 0