gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 19:48:31 26 4
gpt4 key购买 nike

我已经使用 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;
}

最佳答案

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

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

@end

//implementation

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

关于objective-c - 如何使 FMDB 的数据库成为单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5875518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com