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;
}
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