如今ios裏使用的數據庫通常都是Sqlite,可是使用Sqlite有個不太好的地方就是在多線程的時候,會出現問題,sqlite只能打開一個讀或者寫連結。這樣的話多線程就會碰到資源佔用的問題。ios
我使用多線程的簡單例子:sql
SqliteManager.h 文件:數據庫
#import <Foundation/Foundation.h> @interface SqliteManager : NSObject +(instancetype)shareSqliteManager; - (BOOL)insertUserInfo;
SqliteManager.m文件多線程
#import "SqliteManager.h" #import "FMDB.h" @interface SqliteManager () @property(nonatomic , strong)FMDatabaseQueue *fmdbQueue; @end @implementation SqliteManager + (instancetype)shareSqliteManager{ static SqliteManager *manager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ manager = [[SqliteManager alloc] init]; }); return manager; } - (instancetype)init{ if (self = [super init]) { NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString *filePath = [document stringByAppendingPathComponent:@"Umine.sqlite"]; _fmdbQueue = [FMDatabaseQueue databaseQueueWithPath:filePath]; [_fmdbQueue inDatabase:^(FMDatabase *db) { [db open]; //建立好友表 BOOL result=[db executeUpdate:@"CREATE TABLE IF NOT EXISTS userInfo (mobile text , username text ,nickname text, gender text , e_username text PRIMARY KEY,remark_info text, head_pic_url text);"]; if (result) { DLog(@"創用戶表成功"); }else{ DLog(@"創用戶表失敗"); } [db close]; }]; DLog(@"%@",filePath); } return self; } #pragma mark --- 好友信息操做 --- - (BOOL)insertUserInfo{ NSString *sql = [NSString stringWithFormat:@"insert into %@ (mobile,username,nickname,remark_info,gender,e_username,head_pic_url) values (?,?,?,?,?,?,?)",tableName]; __block BOOL result = NO; [_fmdbQueue inDatabase:^(FMDatabase *db) { [db open]; result = [db executeUpdate:sql,model.mobile,model.username,model.nickname,model.remark_info, model.gender,model.e_username,model.head_pic_url]; [db close]; }]; return result; }