摘要:本文将带你了解IOS开发入门之ios常用数据库、完美无缺,希望本文对大家学ios有所帮助。
本文将带你了解IOS开发入门之ios常用数据库、完美无缺,希望本文对大家学ios有所帮助。
直接copy过去就能用,我们不用再去造轮子,现在的xocod9.4更加人性化了,不用再添加依赖库,这点苹果你让我开始喜欢了,哈哈、
需要这兄弟拉进去的哈
下班标的1,2,3,4就是就截图的4个文件,
[TestDBModel clearTable]; //清空数据库
NSLog(@"前[TestDBModel findAll]=%@",[TestDBModel findAll]);
NSArray *arr1 = @[@"哈哈",@"嘻嘻",@"呵呵"];
NSMutableArray *mArr = [[NSMutableArray alloc] init];
for (int i = 0; i < arr1.count; i++) {
TestDBModel *test = [[TestDBModel alloc] init];
test.name = arr1[i];
if (i==1) {
test.sexNum = 100;
test.isDoctor = YES;
}else{
test.sexNum = i;
test.isDoctor = NO;
}
[mArr addObject:test];
}
[TestDBModel saveObjects:mArr];
NSLog(@"后[TestDBModel findAll]=%@",[TestDBModel findAll]);
===================1//// DBHelper.h// Doctor//// Created by zrq on 15/10/8.// Copyright © 2015年 zrq. All rights reserved.//
#import <Foundation/Foundation.h>#import "FMDB.h"
@interface DBHelper : NSObject
@property (nonatomic, retain, readonly) FMDatabaseQueue *dbQueue;
+ (DBHelper *)shareInstance;
+ (NSString *)dbPath;
- (BOOL)changeDBWithDirectoryName:(NSString *)directoryName;
@end
===================2//// DBHelper.m// Doctor//// Created by zrq on 15/10/8.// Copyright © 2015年 zrq. All rights reserved.//
#import "DBHelper.h"#import "DBModel.h"#import <objc/runtime.h>
@interface DBHelper()
@property (nonatomic, retain) FMDatabaseQueue *dbQueue;
@end
@implementation DBHelper
static DBHelper *_instance = nil;
+ (instancetype)shareInstance{ static dispatch_once_t onceToken ; dispatch_once(&onceToken, ^{ _instance = [[super allocWithZone:NULL] init] ; }) ; return _instance;}
+ (NSString *)dbPathWithDirectoryName:(NSString *)directoryName{ NSString *docsdir = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSFileManager *filemanage = [NSFileManager defaultManager]; if (directoryName == nil || directoryName.length == 0) { docsdir = [docsdir stringByAppendingPathComponent:@"ZrqDB"]; } else { docsdir = [docsdir stringByAppendingPathComponent:directoryName]; } BOOL isDir; BOOL exit =[filemanage fileExistsAtPath:docsdir isDirectory:&isDir]; if (!exit || !isDir) { [filemanage createDirectoryAtPath:docsdir withIntermediateDirectories:YES attributes:nil error:nil]; } // NSString *dbpath = [docsdir stringByAppendingPathComponent:[NSString stringWithFormat:@"D%@.sqlite",UDString(DOCTOR_ID)]]; NSString *dbpath = [docsdir stringByAppendingPathComponent:[NSString stringWithFormat:@"D255.sqlite"]]; return dbpath;}
+ (NSString *)dbPath{ return [self dbPathWithDirectoryName:nil];}
- (FMDatabaseQueue *)dbQueue{ if (_dbQueue == nil) { _dbQueue = [[FMDatabaseQueue alloc] initWithPath:[self.class dbPath]]; } return _dbQueue;}
- (BOOL)changeDBWithDirectoryName:(NSString *)directoryName{ if (_instance.dbQueue) { _instance.dbQueue = nil; } _instance.dbQueue = [[FMDatabaseQueue alloc] initWithPath:[DBHelper dbPathWithDirectoryName:directoryName]]; int numClasses; Class *classes = NULL; numClasses = objc_getClassList(NULL,0); if (numClasses >0 ) { classes = (__unsafe_unretained Class *)malloc(sizeof(Class) * numClasses); numClasses = objc_getClassList(classes, numClasses); for (int i = 0; i < numClasses; i++) { if (class_getSuperclass(classes[i]) == [DBModel class]){ id class = classes[i]; [class performSelector:@selector(createTable) withObject:nil]; } } free(classes); } return YES;}
+ (id)allocWithZone:(struct _NSZone *)zone{ return [DBHelper shareInstance];}
- (id)copyWithZone:(struct _NSZone *)zone{ return [DBHelper shareInstance];}
#if ! __has_feature(objc_arc)- (oneway void)release{ }
- (id)autorelease{ return _instance;}
- (NSUInteger)retainCount{ return 1;}#endif@end
===================3//// DBModel.h// Doctor//// Created by zrq on 15/10/8.// Copyright © 2015年 zrq. All rights reserved.//
#import <Foundation/Foundation.h>
/** SQLite五种数据类型 */#define SQLTEXT @"TEXT"#define SQLINTEGER @"INTEGER"#define SQLREAL @"REAL"#define SQLBLOB @"BLOB"#define SQLNULL @"NULL"#define PrimaryKey @"primary key"
#define primaryId @"pk"
@interface DBModel : NSObject
/** 主键 id */@property (nonatomic, assign) int pk;/** 列名 */@property (retain, readonly, nonatomic) NSMutableArray *columeNames;/** 列类型 */@property (retain, readonly, nonatomic) NSMutableArray *columeTypes;
/** * 获取该类的所有属性 */+ (NSDictionary *)getPropertys;
/** 获取所有属性,包括主键 */+ (NSDictionary *)getAllProperties;
/** 数据库中是否存在表 */+ (BOOL)isExistInTable;
/** 表中的字段*/+ (NSArray *)getColumns;
/** 保存或更新 * 如果不存在主键,保存, * 有主键,则更新 */- (BOOL)saveOrUpdate;/** 保存单个数据 */- (BOOL)save;/** 批量保存数据 */+ (BOOL)saveObjects:(NSArray *)array;/** 更新单个数据 */- (BOOL)update;/** 批量更新数据*/+ (BOOL)updateObjects:(NSArray *)array;/** 删除单个数据 */- (BOOL)deleteObject;/** 批量删除数据 */+ (BOOL)deleteObjects:(NSArray *)array;/** 通过条件删除数据 */+ (BOOL)deleteObjectsByCriteria:(NSString *)criteria;/** 通过条件删除 (多参数)--2 */+ (BOOL)deleteObjectsWithFormat:(NSString *)format, ...;/** 清空表 */+ (BOOL)clearTable;
/** 查询全部数据 */+ (NSArray *)findAll;
/** 通过主键查询 */+ (instancetype)findByPK:(int)inPk;/** 通过条件查询 */+ (instancetype)findFirstWithFormat:(NSString *)format, ...;
/** 查找某条数据 */+ (instancetype)findFirstByCriteria:(NSString *)criteria;
+ (NSArray *)findWithFormat:(NSString *)format, ...;
/** 通过条件查找数据 * 这样可以进行分页查询 @" WHERE pk > 5 limit 10" */+ (NSArray *)findByCriteria:(NSString *)criteria;/** * 创建表 * 如果已经创建,返回YES */+ (BOOL)createTable;
#pragma mark - must be override method/** 如果子类中有一些property不需要创建数据库字段,那么这个方法必须在子类中重写 */+ (NSArray *)transients;
@end
===================4//// DBModel.m// Doctor//// Created by zrq on 15/10/8.// Copyright © 2015年 zrq. All rights reserved.//
#import "DBModel.h"#import <objc/runtime.h>#import "DBHelper.h"
@implementation DBModel
#pragma mark - override method+ (void)initialize{ if (self != [DBModel self]) { [self createTable]; }}
- (instancetype)init{ self = [super init]; if (self) { NSDictionary *dic = [self.class getAllProperties]; _columeNames = [[NSMutableArray alloc] initWithArray:[dic objectForKey:@"name"]]; _columeTypes = [[NSMutableArray alloc] initWithArray:[dic objectForKey:@"type"]]; } return self;}
#pragma mark - base method/** * 获取该类的所有属性 */+ (NSDictionary *)getPropertys{ NSMutableArray *proNames = [NSMutableArray array]; NSMutableArray *proTypes = [NSMutableArray array]; NSArray *theTransients = [[self class] transients]; unsigned int outCount, i; 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@"]) { [proTypes addObject:SQLTEXT]; } else if ([propertyType hasPrefix:@"Ti"]||[propertyType hasPrefix:@"TI"]||[propertyType hasPrefix:@"Ts"]||[propertyType hasPrefix:@"TS"]||[propertyType hasPrefix:@"TB"]) { [proTypes addObject:SQLINTEGER]; } else { [proTypes addObject:SQLREAL]; } } free(properties); return [NSDictionary dictionaryWithObjectsAndKeys:proNames,@"name",proTypes,@"type",nil];}
/** 获取所有属性,包含主键pk */+ (NSDictionary *)getAllProperties{ NSDictionary *dict = [self.class getPropertys]; //NSLog(@"该类所有属性:%@",[self.class getPropertys]); NSMutableArray *proNames = [NSMutableArray array]; NSMutableArray *proTypes = [NSMutableArray array]; [proNames addObject:primaryId]; [proTypes addObject:[NSString stringWithFormat:@"%@ %@",SQLINTEGER,PrimaryKey]]; [proNames addObjectsFromArray:[dict objectForKey:@"name"]]; [proTypes addObjectsFromArray:[dict objectForKey:@"type"]]; //NSLog(@"%@",[NSDictionary dictionaryWithObjectsAndKeys:proNames,@"name",proTypes,@"type",nil]); return [NSDictionary dictionaryWithObjectsAndKeys:proNames,@"name",proTypes,@"type",nil];}
/** 数据库中是否存在表 */+ (BOOL)isExistInTable{ __block BOOL res = NO; DBHelper *jkDB = [DBHelper shareInstance]; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); res = [db tableExists:tableName]; }]; return res;}
/** 获取列名 */+ (NSArray *)getColumns{ DBHelper *jkDB = [DBHelper shareInstance]; NSMutableArray *columns = [NSMutableArray array]; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); FMResultSet *resultSet = [db getTableSchema:tableName]; while ([resultSet next]) { NSString *column = [resultSet stringForColumn:@"name"]; [columns addObject:column]; } }]; return [columns copy];}
/** * 创建表 * 如果已经创建,返回YES */+ (BOOL)createTable{ __block BOOL res = YES; DBHelper *jkDB = [DBHelper shareInstance]; [jkDB.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) { NSString *tableName = NSStringFromClass(self.class); NSString *columeAndType = [self.class getColumeAndTypeString]; //NSLog(@"columeAndType= %@",columeAndType); NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(%@);",tableName,columeAndType]; if (![db executeUpdate:sql]) { res = NO; *rollback = YES; return; }; NSMutableArray *columns = [NSMutableArray array]; FMResultSet *resultSet = [db getTableSchema:tableName]; while ([resultSet next]) { NSString *column = [resultSet stringForColumn:@"name"]; [columns addObject:column]; } NSDictionary *dict = [self.class getAllProperties]; NSArray *properties = [dict objectForKey:@"name"]; NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",columns]; //过滤数组 NSArray *resultArray = [properties filteredArrayUsingPredicate:filterPredicate]; for (NSString *column in resultArray) { NSUInteger index = [properties indexOfObject:column]; NSString *proType = [[dict objectForKey:@"type"] objectAtIndex:index]; NSString *fieldSql = [NSString stringWithFormat:@"%@ %@",column,proType]; NSString *sql = [NSString stringWithFormat:@"ALTER TABLE %@ ADD COLUMN %@ ",NSStringFromClass(self.class),fieldSql]; if (![db executeUpdate:sql]) { res = NO; *rollback = YES; return ; } } }]; return res;}
/** * 创建表 * 如果已经创建,返回YES *///+ (BOOL)createTable//{// FMDatabase *db = [FMDatabase databaseWithPath:[JKDBHelper dbPath]];// if (![db open]) {// NSLog(@"数据库打开失败!");// return NO;// }//// NSString *tableName = NSStringFromClass(self.class);// NSString *columeAndType = [self.class getColumeAndTypeString];// NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(%@);",tableName,columeAndType];// if (![db executeUpdate:sql]) {// return NO;// }//// NSMutableArray *columns = [NSMutableArray array];// FMResultSet *resultSet = [db getTableSchema:tableName];// while ([resultSet next]) {// NSString *column = [resultSet stringForColumn:@"name"];// [columns addObject:column];// }// NSDictionary *dict = [self.class getAllProperties];// NSArray *properties = [dict objectForKey:@"name"];// NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",columns];// //过滤数组// NSArray *resultArray = [properties filteredArrayUsingPredicate:filterPredicate];//// for (NSString *column in resultArray) {// NSUInteger index = [properties indexOfObject:column];// NSString *proType = [[dict objectForKey:@"type"] objectAtIndex:index];// NSString *fieldSql = [NSString stringWithFormat:@"%@ %@",column,proType];// NSString *sql = [NSString stringWithFormat:@"ALTER TABLE %@ ADD COLUMN %@ ",NSStringFromClass(self.class),fieldSql];// if (![db executeUpdate:sql]) {// return NO;// }// }// [db close];// return YES;//}
- (BOOL)saveOrUpdate{ id primaryValue = [self valueForKey:primaryId]; if ([primaryValue intValue] <= 0) { return [self save]; } return [self update];}
- (BOOL)save{ NSString *tableName = NSStringFromClass(self.class); NSMutableString *keyString = [NSMutableString string]; NSMutableString *valueString = [NSMutableString string]; NSMutableArray *insertValues = [NSMutableArray array]; for (int i = 0; i < self.columeNames.count; i++) { NSString *proname = [self.columeNames objectAtIndex:i]; if ([proname isEqualToString:primaryId]) { continue; } [keyString appendFormat:@"%@,", proname]; [valueString appendString:@"?,"]; id value = [self valueForKey:proname]; if (!value) { value = @""; } [insertValues addObject:value]; } [keyString deleteCharactersInRange:NSMakeRange(keyString.length - 1, 1)]; [valueString deleteCharactersInRange:NSMakeRange(valueString.length - 1, 1)]; DBHelper *jkDB = [DBHelper shareInstance]; __block BOOL res = NO; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@(%@) VALUES (%@);", tableName, keyString, valueString]; res = [db executeUpdate:sql withArgumentsInArray:insertValues]; self.pk = res?[NSNumber numberWithLongLong:db.lastInsertRowId].intValue:0; NSLog(res?@"插入成功":@"插入失败"); }]; return res;}
/** 批量保存用户对象 */+ (BOOL)saveObjects:(NSArray *)array{ NSLog(@"BD保存002==>[DBModel class]= %@",[DBModel class]); //判断是否是JKBaseModel的子类 for (DBModel *model in array) { if (![model isKindOfClass:[DBModel class]]) { return NO; } } __block BOOL res = YES; DBHelper *jkDB = [DBHelper shareInstance]; // 如果要支持事务 [jkDB.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) { for (DBModel *model in array) { NSString *tableName = NSStringFromClass(model.class); NSMutableString *keyString = [NSMutableString string]; NSMutableString *valueString = [NSMutableString string]; NSMutableArray *insertValues = [NSMutableArray array]; for (int i = 0; i < model.columeNames.count; i++) { NSString *proname = [model.columeNames objectAtIndex:i]; if ([proname isEqualToString:primaryId]) { continue; } [keyString appendFormat:@"%@,", proname]; [valueString appendString:@"?,"]; id value = [model valueForKey:proname]; if (!value) { value = @""; } [insertValues addObject:value]; } [keyString deleteCharactersInRange:NSMakeRange(keyString.length - 1, 1)]; [valueString deleteCharactersInRange:NSMakeRange(valueString.length - 1, 1)]; NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@(%@) VALUES (%@);", tableName, keyString, valueString]; BOOL flag = [db executeUpdate:sql withArgumentsInArray:insertValues]; model.pk = flag?[NSNumber numberWithLongLong:db.lastInsertRowId].intValue:0; NSLog(flag?@"插入成功":@"插入失败"); if (!flag) { res = NO; *rollback = YES; return; } } }]; return res;}
/** 更新单个对象 */- (BOOL)update{ DBHelper *jkDB = [DBHelper shareInstance]; __block BOOL res = NO; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); id primaryValue = [self valueForKey:primaryId]; if (!primaryValue || primaryValue <= 0) { return ; } NSMutableString *keyString = [NSMutableString string]; NSMutableArray *updateValues = [NSMutableArray array]; for (int i = 0; i < self.columeNames.count; i++) { NSString *proname = [self.columeNames objectAtIndex:i]; if ([proname isEqualToString:primaryId]) { continue; } [keyString appendFormat:@" %@=?,", proname]; id value = [self valueForKey:proname]; if (!value) { value = @""; } [updateValues addObject:value]; } //删除最后那个逗号 [keyString deleteCharactersInRange:NSMakeRange(keyString.length - 1, 1)]; NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET %@ WHERE %@ = ?;", tableName, keyString, primaryId]; [updateValues addObject:primaryValue]; res = [db executeUpdate:sql withArgumentsInArray:updateValues]; NSLog(res?@"更新成功":@"更新失败"); }]; return res;}
/** 批量更新用户对象*/+ (BOOL)updateObjects:(NSArray *)array{ for (DBModel *model in array) { if (![model isKindOfClass:[DBModel class]]) { return NO; } } __block BOOL res = YES; DBHelper *jkDB = [DBHelper shareInstance]; // 如果要支持事务 [jkDB.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) { for (DBModel *model in array) { NSString *tableName = NSStringFromClass(model.class); id primaryValue = [model valueForKey:primaryId]; if (!primaryValue || primaryValue <= 0) { res = NO; *rollback = YES; return; } NSMutableString *keyString = [NSMutableString string]; NSMutableArray *updateValues = [NSMutableArray array]; for (int i = 0; i < model.columeNames.count; i++) { NSString *proname = [model.columeNames objectAtIndex:i]; if ([proname isEqualToString:primaryId]) { continue; } [keyString appendFormat:@" %@=?,", proname]; id value = [model valueForKey:proname]; if (!value) { value = @""; } [updateValues addObject:value]; } //删除最后那个逗号 [keyString deleteCharactersInRange:NSMakeRange(keyString.length - 1, 1)]; NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET %@ WHERE %@=?;", tableName, keyString, primaryId]; [updateValues addObject:primaryValue]; BOOL flag = [db executeUpdate:sql withArgumentsInArray:updateValues]; NSLog(flag?@"更新成功":@"更新失败"); if (!flag) { res = NO; *rollback = YES; return; } } }]; return res;}
/** 删除单个对象 */- (BOOL)deleteObject{ DBHelper *jkDB = [DBHelper shareInstance]; __block BOOL res = NO; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); id primaryValue = [self valueForKey:primaryId]; if (!primaryValue || primaryValue <= 0) { return ; } NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = ?",tableName,primaryId]; res = [db executeUpdate:sql withArgumentsInArray:@[primaryValue]]; NSLog(res?@"删除成功":@"删除失败"); }]; return res;}
/** 批量删除用户对象 */+ (BOOL)deleteObjects:(NSArray *)array{ for (DBModel *model in array) { if (![model isKindOfClass:[DBModel class]]) { return NO; } } __block BOOL res = YES; DBHelper *jkDB = [DBHelper shareInstance]; // 如果要支持事务 [jkDB.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) { for (DBModel *model in array) { NSString *tableName = NSStringFromClass(model.class); id primaryValue = [model valueForKey:primaryId]; if (!primaryValue || primaryValue <= 0) { return ; } NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ = ?",tableName,primaryId]; BOOL flag = [db executeUpdate:sql withArgumentsInArray:@[primaryValue]]; NSLog(flag?@"删除成功":@"删除失败"); if (!flag) { res = NO; *rollback = YES; return; } } }]; return res;}
/** 通过条件删除数据 */+ (BOOL)deleteObjectsByCriteria:(NSString *)criteria{ DBHelper *jkDB = [DBHelper shareInstance]; __block BOOL res = NO; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ %@ ",tableName,criteria]; res = [db executeUpdate:sql]; NSLog(res?@"删除成功":@"删除失败"); }]; return res;}
/** 通过条件删除 (多参数)--2 */+ (BOOL)deleteObjectsWithFormat:(NSString *)format, ...{ va_list ap; va_start(ap, format); NSString *criteria = [[NSString alloc] initWithFormat:format locale:[NSLocale currentLocale] arguments:ap]; va_end(ap); return [self deleteObjectsByCriteria:criteria];}
/** 清空表 */+ (BOOL)clearTable{ DBHelper *jkDB = [DBHelper shareInstance]; __block BOOL res = NO; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@",tableName]; res = [db executeUpdate:sql]; NSLog(res?@"清空成功":@"清空失败"); }]; return res;}
///0708DB/** 查询全部数据 */+ (NSArray *)findAll{ NSLog(@"jkdb---%s",__func__); DBHelper *jkDB = [DBHelper shareInstance]; NSMutableArray *users = [NSMutableArray array]; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@",tableName]; FMResultSet *resultSet = [db executeQuery:sql]; while ([resultSet next]) { DBModel *model = [[self.class alloc] init]; for (int i=0; i< model.columeNames.count; i++) { NSString *columeName = [model.columeNames objectAtIndex:i]; NSString *columeType = [model.columeTypes objectAtIndex:i]; if ([columeType isEqualToString:SQLTEXT]) { [model setValue:[resultSet stringForColumn:columeName] forKey:columeName]; } else { [model setValue:[NSNumber numberWithLongLong:[resultSet longLongIntForColumn:columeName]] forKey:columeName]; } } [users addObject:model]; FMDBRelease(model); } }]; return users;}
+ (instancetype)findFirstWithFormat:(NSString *)format, ...{ va_list ap; va_start(ap, format); NSString *criteria = [[NSString alloc] initWithFormat:format locale:[NSLocale currentLocale] arguments:ap]; va_end(ap); return [self findFirstByCriteria:criteria];}
/** 查找某条数据 */+ (instancetype)findFirstByCriteria:(NSString *)criteria{ NSArray *results = [self.class findByCriteria:criteria]; if (results.count < 1) { return nil; } return [results firstObject];}
+ (instancetype)findByPK:(int)inPk{ NSString *condition = [NSString stringWithFormat:@"WHERE %@=%d",primaryId,inPk]; return [self findFirstByCriteria:condition];}
+ (NSArray *)findWithFormat:(NSString *)format, ...{ va_list ap; va_start(ap, format); NSString *criteria = [[NSString alloc] initWithFormat:format locale:[NSLocale currentLocale] arguments:ap]; va_end(ap); return [self findByCriteria:criteria];}
/** 通过条件查找数据 */+ (NSArray *)findByCriteria:(NSString *)criteria{ DBHelper *jkDB = [DBHelper shareInstance]; NSMutableArray *users = [NSMutableArray array]; [jkDB.dbQueue inDatabase:^(FMDatabase *db) { NSString *tableName = NSStringFromClass(self.class); NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ %@",tableName,criteria]; FMResultSet *resultSet = [db executeQuery:sql]; while ([resultSet next]) { DBModel *model = [[self.class alloc] init]; for (int i=0; i< model.columeNames.count; i++) { NSString *columeName = [model.columeNames objectAtIndex:i]; NSString *columeType = [model.columeTypes objectAtIndex:i]; if ([columeType isEqualToString:SQLTEXT]) { [model setValue:[resultSet stringForColumn:columeName] forKey:columeName]; } else { [model setValue:[NSNumber numberWithLongLong:[resultSet longLongIntForColumn:columeName]] forKey:columeName]; } } [users addObject:model]; FMDBRelease(model); } }]; return users;}
#pragma mark - util method+ (NSString *)getColumeAndTypeString{ NSMutableString* pars = [NSMutableString string]; NSDictionary *dict = [self.class getAllProperties]; NSMutableArray *proNames = [dict objectForKey:@"name"]; NSMutableArray *proTypes = [dict objectForKey:@"type"]; for (int i=0; i< proNames.count; i++) { [pars appendFormat:@"%@ %@",[proNames objectAtIndex:i],[proTypes objectAtIndex:i]]; if(i+1 != proNames.count) { [pars appendString:@","]; } } return pars;}
- (NSString *)description{ NSString *result = @""; NSDictionary *dict = [self.class getAllProperties]; NSMutableArray *proNames = [dict objectForKey:@"name"]; for (int i = 0; i < proNames.count; i++) { NSString *proName = [proNames objectAtIndex:i]; id proValue = [self valueForKey:proName]; result = [result stringByAppendingFormat:@"%@:%@\n",proName,proValue]; } return result;}
#pragma mark - must be override method/** 如果子类中有一些property不需要创建数据库字段,那么这个方法必须在子类中重写 */+ (NSArray *)transients{ return [NSArray array];}
@end
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之IOS频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号