iOS根据模型获取模型字段以及字段的类型(用于创建数据库的表)

BitTigerio 2018-03-07

#pragma mark - base method
/**
* 获取该类的所有属性
*/
+ (NSDictionary *)getPropertys
{
NSMutableArray *proNames = [NSMutableArray array];
NSMutableArray *proTypes = [NSMutableArray array];
unsigned int outCount, i;
//获取模型中有多少个字段,以及笛子包含内容,[self class]不是类本身,谁调用这个方法,获取就是那个类
objc_property_t *properties = class_copyPropertyList([self class], &outCount);

for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
//获取属性名(字段名称)
NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
if ([theTransients containsObject:propertyName]) {
continue;
}
[proNames addObject:propertyName];
//获取属性类型等参数(字段的类型)
NSString *propertyType = [NSString stringWithCString: property_getAttributes(property) encoding:NSUTF8StringEncoding];
/*
各种符号对应类型,部分类型在新版SDK中有所变化,如long 和long long
c char C unsigned char
i int I unsigned int
l long L unsigned long
s short S unsigned short
d double D unsigned double
f float F unsigned float
q long long Q unsigned long long
B BOOL
@ 对象类型 //指针 对象类型 如NSString 是@“NSString”


64位下long 和long long 都是Tq
SQLite 默认支持五种数据类型TEXT、INTEGER、REAL、BLOB、NULL
因为在项目中用的类型不多,故只考虑了少数类型
*/
if ([propertyType hasPrefix:@"T@\"NSString\""]) {
[proTypes addObject:SQLTEXT];
} else if ([propertyType hasPrefix:@"T@\"NSData\""]) {
[proTypes addObject:SQLBLOB];
} else if ([propertyType hasPrefix:@"Ti"]||[propertyType hasPrefix:@"TI"]||[propertyType hasPrefix:@"Ts"]||[propertyType hasPrefix:@"TS"]||[propertyType hasPrefix:@"TB"]||[propertyType hasPrefix:@"Tq"]||[propertyType hasPrefix:@"TQ"]) {
[proTypes addObject:SQLINTEGER];
} else {
[proTypes addObject:SQLREAL];
}

}
free(properties);

return [NSDictionary dictionaryWithObjectsAndKeys:proNames,@"name",proTypes,@"type",nil];
}


相关推荐