项目中经常遇到数据持久化的问题,直接使用FMDB比较麻烦,我想直接存Model数据源,然后直接建表,存储。
思路是这样的:
1. 建表,传入Model的Class,根据Model的Class拿到Model里面的所有成员变量,然后把成员变量拼接成SQL语句,然后执行,根据Model的成员变量自动建表。
2. 存,传入装有Model数据的数组Arr,或者直接Model数据,使用Runtime拿到这个Model的键值对,然后拼接成插入SQL语句。
3. 取。取比较多样化,可以去整个表数据,也可以根据条件去取。当取到数据之后,弄成字典键值对。然后根据这个ModelClass创建对象,然后使用键值对给这个Model赋值,存入数组,然后传出。
1.建表
/**
* 创建表
*
* @param tabName 表名
* @param model 数据model
*
* @return
*/
+ (instancetype)instantiationSqlTabName:(NSString *)tabName WithModelClass:(Class)modelClass{
NSString* sql=[NSString stringWithFormat:@"create table if not exists %@ (id integer primary key autoincrement ",tabName];
for (NSString *str in [modelClass GetPropertyKey]) {
NSString *strq = [NSString stringWithFormat:@",%@ ",str];
sql = [sql stringByAppendingString:strq];
}
sql = [sql stringByAppendingString:@")"];
NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fileName=[doc stringByAppendingPathComponent:[NSString stringWithFormat:@"sql.sqlite"]];
NSLog(@"%@",fileName);
ZCSqlTool *sqltool = [ZCSqlTool new];
sqltool.db = [[FMDatabase alloc]initWithPath:fileName];
if ([sqltool.db open]) {
[sqltool.db executeUpdate:sql];
}else{
NSLog(@"创建失败");
}
return sqltool;
}
2.存
/**
* 插入数据
*
* @param tabName 表名
* @param data 数据
* @param isDelete 是否清空该表之前的数据
*
* @return
*/
- (BOOL)insertDataTabName:(NSString *)tabName WithData:(id)data WithdeleteFrom:(BOOL)isDelete{
if (isDelete == YES) {
NSString *sql = [NSString stringWithFormat:@"delete from %@",tabName];
BOOL isDeleteResult = [self.db executeUpdate:sql];
if (isDeleteResult) {
return [self carriedOutInsertDataTabName:tabName WithDatas:data];
}else{
NSLog(@"删除失败");
return NO;
}
}
return [self carriedOutInsertDataTabName:tabName WithDatas:data];
}
3.取
- (BOOL)conditionalDeletionTabName:(NSString *)tableName condition:(NSString *)condition,...NS_REQUIRES_NIL_TERMINATION{
va_list ap;
va_start(ap, condition);
NSString *str;
NSString *str1 = [[condition componentsSeparatedByString:@"="] firstObject];
NSString *str2 = [[condition componentsSeparatedByString:@"="] lastObject];
NSString *sqlStr = [NSString stringWithFormat:@"delete from %@ where %@ = \"%@\"",tableName,str1,str2];
while ((str=va_arg(ap, NSString*))) {
NSArray *arr = [str componentsSeparatedByString:@"="];
if (arr.count == 2 && [[arr lastObject] length] > 0) {
sqlStr = [NSString stringWithFormat:@"%@ and %@ = \"%@\"",sqlStr,[arr firstObject],[arr lastObject]];
}else
{
NSLog(@"请输入正确格式的数据");
return nil;
}
}
va_end(ap);
BOOL isInsertData;
if ([self.db open]) {
isInsertData = [self.db executeUpdate:sqlStr];
[self.db close];
}
return isInsertData;
}
直接存入Model数据,取也是取得就是Model数组。超级方便。不管是缓存 还是其他 业务,两句代码搞定一切