#import <Foundation/Foundation.h>
#import "AppModel.h"
@interface LimitDBManager : NSObject
+ (instancetype)sharedInstance;
//type :浏览,下载,收藏
//添加
- (void)addAppInfo:(AppModel*)model type:(NSString*)type;
//删除
- (void)deleteAppInfo:(AppModel*)model type:(NSString*)type;
//根据type读取AppInfo的列表
- (NSArray*)readAppInfoList:(NSString*)type;
//判断类型为type的app 是否存在表中
- (BOOL)isAppInfoExists:(AppModel*)model type:(NSString*)type;
@end
//=====================================================================//
#import "LimitDBManager.h"
#import "FMDatabase.h"@interface LimitDBManager()
{
FMDatabase *_db; //数据库实例
}
@end
@implementation LimitDBManager
+ (instancetype)sharedInstance
{
static LimitDBManager *s_dbManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
s_dbManager = [[LimitDBManager alloc]init];
});
return s_dbManager;
}
- (NSString*)dbPath
{
return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/limit.db"];
}
- (id)init{
if (self = [super init]) {
NSLog(@"dbPath = %@",[self dbPath]);
_db = [[FMDatabase alloc]initWithPath:[self dbPath]];
if ([_db open]) {
[self createTable];
}
}
return self;
}
- (void)createTable
{
NSString *sql = @"create table if not exists appInfo(serialId integer primary key autoincrement,appId text,appName text,appIconUrl text,appDesc text,type text)";
if (![_db executeUpdate:sql]) {
NSLog(@"创建表失败");
}
}
//type :浏览,下载,收藏
//添加
- (void)addAppInfo:(AppModel*)model type:(NSString*)type
{
NSString *sql = @"insert into appInfo(appId,appName,appIconUrl,appDesc,type) values(?,?,?,?,?)";
if (![_db executeUpdate:sql,model.applicationId,model.name,model.iconUrl,model.description,type]) {
NSLog(@"插入记录失败");
}
}
//删除
- (void)deleteAppInfo:(AppModel*)model type:(NSString*)type
{
NSString *sql = @"delete from appInfo where appId = ? AND type = ?";
if (![_db executeUpdate:sql,model.applicationId,type]) {
NSLog(@"删除数据失败");
}
}
//根据type读取AppInfo的列表
- (NSArray*)readAppInfoList:(NSString*)type
{
NSMutableArray *appArray = [NSMutableArray array];
NSString *sql = @"select * from appInfo where type = ?";
FMResultSet *resultSet = [_db executeQuery:sql,type];
while (resultSet.next) {
AppModel *appModel = [[AppModel alloc]init];
appModel.applicationId = [resultSet stringForColumn:@"appId"];
appModel.name = [resultSet stringForColumn:@"appName"];
appModel.iconUrl = [resultSet stringForColumn:@"appIconUrl"];
appModel.description = [resultSet stringForColumn:@"appDesc"];
[appArray addObject:appModel];
}
[resultSet close];
return appArray;
}
//判断类型为type的app 是否存在表中
- (BOOL)isAppInfoExists:(AppModel*)model type:(NSString*)type{
BOOL isExist = NO;
NSString *sql = @"select * from appInfo where appId = ? and type = ?";
FMResultSet *resultSet = [_db executeQuery:sql,model.applicationId,type];
if (resultSet.next) {
isExist = YES;
}
[resultSet close];
return isExist;
}
@end