1. 程式人生 > >ios FMDB多執行緒"is currently in use", "database is locked"問題的解決

ios FMDB多執行緒"is currently in use", "database is locked"問題的解決

is currently in use” 出現的場景是這樣的,多執行緒操作資料庫,每個執行緒都使用了FMDatabase例項

FMDatabase是不具備執行緒安全的,如果兩個執行緒中同時操作資料庫,就會”is currently in use” ;FMDatabasequeue其實是一個排程佇列(G-C-D),資料庫的操作必須是順序執行,不能兩個資料庫的操作同時執行,如果是兩個執行緒各自建立了FMDatabaseQueue的例項,執行緒同時執行時,就會出現相同的資料庫操作同時觸發,導致”database is locked“,所以必須是一個FMDatabaseQueue例項下,多個執行緒下同時操作,其實是在排在同一個佇列中逐一操作的,沒有同時操作。


解決辦法:

自定義一個 DatabaseHelper類

DatabaseHelper.h

#import <Foundation/Foundation.h>
#import "FMDB.h"

@interface DatabaseHelper : NSObject
@property(nonatomic,strong)NSString *dbName;
+(DatabaseHelper*) sharedInstance;
-(void)inDatabase:(void(^)(FMDatabase*))block;
- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block;
- (void)close;

@end

DatabaseHelper.m

#import "DatabaseHelper.h"

@interface DatabaseHelper()

@property(nonatomic,strong)NSString *dbPath;

@end
@implementation DatabaseHelper
{
    FMDatabaseQueue* queue;
}

-(NSString *)dbPath {
    if (!_dbPath) {
        _dbPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"datas.db"];
        NSLog(@"%@",_dbPath);
    }
    return _dbPath;
}

-(id) init
{
    self = [super init];
    if(self){
        //NSString *dbFilePath = [PathResolver databaseFilePath];
        queue = [FMDatabaseQueue databaseQueueWithPath:self.dbPath];
    }
    return self;
}

+(DatabaseHelper*)sharedInstance
{
    static dispatch_once_t pred = 0;
    __strong static id _sharedObject = nil;
    dispatch_once(&pred, ^{
        _sharedObject = [[self alloc] init];
    });
    return _sharedObject;
}

-(void)inDatabase:(void(^)(FMDatabase*))block
{
    [queue inDatabase:^(FMDatabase *db){
        block(db);
    }];
}

- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block {
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        block(db,rollback);
    }];
}

- (void)close {
    [queue close];
}
@end

案例:
#import "ViewController.h"
#import "DatabaseHelper.h"
@interface ViewController ()
@property(nonatomic,strong)DatabaseHelper *dbQueue;
@end

@implementation ViewController
-(DatabaseHelper *)dbQueue {
    if (!_dbQueue) {
        _dbQueue = [DatabaseHelper sharedInstance];//單例
    }
    return _dbQueue;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    dispatch_queue_t q1 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    for (int i=0; i<1000; i++) {
        dispatch_async(q1, ^{
            [self.dbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
                BOOL isSucess = [db executeUpdate:@"create table  if not exists test(id INTEGER  PRIMARY KEY AUTOINCREMENT, name TEXT, nameTwo TEXT)"];
                BOOL isSucess2 = [db executeUpdate:@"insert into test(name) values('YKJ')"];
                BOOL isSucess3 = [db executeUpdate:@"insert into test(nameTwo) values('ZJT')"];
                BOOL isSucess4 = [db executeUpdate:@"UPDATE test SET name = 'ting'"];
                BOOL isSucess5 = [db executeUpdate:@"UPDATE test SET nameTwo = 'tingJin'"];
                if (!isSucess || isSucess2 || isSucess3 || isSucess4 || isSucess5) {
                    *rollback = YES;//回滾
                    return;
                }
            }];
        });
    }
    
}
@end



我的業餘技術微信公眾號:YKJGZH,歡迎大家進入