iOS runtime 根據類名獲取屬性的型別和名稱
最近想簡單封裝一下FMDB,簡單實現根據模型建立表的功能。
又研究了下runtime,解析property_getAttributes即可獲得屬性型別名稱等
@protocol Aprotocol <NSObject>
@end
typedef void(^TestBlock)(int age);
@interface Student : NSObject
@property(nonatomic, copy)NSString<Aprotocol> *name ;
@property(nonatomic, assign)int score;
@property
@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
@property char 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