How do I make FMDB's database a singleton

做~自己de王妃 提交于 2019-12-07 08:38:48

问题


I have been using SQLite for awhile now, and have decided to go to FMDB. I need to make it a singleton. Here's my code below; what do I have to change to have FMDB access the singleton 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;
}   

and this is the code I use to initialize the d/b using FMDB:

//-----------------------    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:


Your SQLiteDB class will need to maintain a reference to your FMDatabase so your additional methods will be able to share the same database.

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

@end

//implementation

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


来源:https://stackoverflow.com/questions/5875518/how-do-i-make-fmdbs-database-a-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!