如何使FMDB的数据库成为单例

时间:2011-05-03 20:47:29

标签: objective-c sqlite fmdb

我现在已经使用SQLite了一段时间,并决定去FMDB。我需要让它成为一个单身人士。这是我下面的代码;我需要更改什么才能使FMDB访问单例d / b?

#pragma mark Singleton Methods

+ (SQLiteDB *) sharedSQLiteDB  {

    if(!sharedSQLiteDB)  {
        sharedSQLiteDB = [[SQLiteDB alloc] init];
        [sharedSQLiteDB openCreateDB];  //  check to see if d/b exists
    }
    return sharedSQLiteDB;
}   

这是我用来使用FMDB初始化d / b的代码:

//-----------------------    checkIfDatabaseExists    -----------------|
    - (void) openCreateDB  {

        searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  // Get the path to the database file
        documentPath = [searchPaths objectAtIndex:0];
        databasePath = [documentPath stringByAppendingPathComponent:@"ppcipher.s3db"];
        cDatabasePath = [databasePath cStringUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"d/b path: /%@", databasePath);

        NSString *sqlCommand = @"CREATE TABLE CardData (card_id TEXT PRIMARY KEY NOT NULL, card_name TEXT NOT NULL, "
            @"card_type TEXT, code_val TEXT, create_date TEXT DEFAULT CURRENT_DATE, user_notes TEXT, gps_loc TEXT)"; 
        char * errmsg = nil;   

        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager removeItemAtPath:databasePath error:NULL];  //  <------------  delete d/b  TESTING ONLY! 

        BOOL fileExists = [fileManager fileExistsAtPath:databasePath];
        if(!fileExists)  {
            FMDatabase* db = [FMDatabase databaseWithPath: databasePath]; 

            if (![db open]) {
                NSLog(@"Could not open/create database");
            }

            [db executeUpdate:@"CREATE TABLE CardData (card_id TEXT PRIMARY KEY NOT NULL, card_name TEXT NOT NULL, "
             @"card_type TEXT, code_val TEXT, create_date TEXT DEFAULT CURRENT_DATE, user_notes TEXT, gps_loc TEXT)"];

            if(errmsg != nil)
                NSLog(@"error: %s", errmsg);  //  DEBUGGING ONLY!  (REMOVE when done!)
        }
        return;
    }

1 个答案:

答案 0 :(得分:1)

您的SQLiteDB类需要维护对FMDatabase的引用,以便您的其他方法能够共享同一个数据库。

@interface SQLiteDB : NSObject //Or whatever base class
{
    FMDatabase *_database;
}

@end

//implementation

- (void) openCreateDB  {
   ...
   if(!fileExists)  {
      _database = [[FMDatabase databaseWithPath: databasePath] retain];
   ...
   }
}