gpt4 book ai didi

ios - 如果 iOS sqlite 中不存在数据库,则导入

转载 作者:行者123 更新时间:2023-11-29 12:44:52 25 4
gpt4 key购买 nike

我的问题是它总是在渲染我的应用程序时从资源文件中导入 sqlite 数据库(它已经有很多设置数据)。我第一次呈现我的应用程序时,它从资源文件中导入 sqlite 数据库,然后我将一些数据插入到表中。但是第二次再次渲染,它再次导入并丢失了我插入的记录。以下是我的编码。

如果数据库存在,我想要的不需要导入。

static NaWinDatabase *_database;

+ (NaWinDatabase*)database {
if (_database == nil) {
_database = [[NaWinDatabase alloc] init];
}
return _database;
}

- (id)init {
if ((self = [super init])) {
NSString *sqLiteDb = [[NSBundle mainBundle] pathForResource:@"nawin" ofType:@"sqlite3"];

if (sqlite3_open([sqLiteDb UTF8String], &_database) != SQLITE_OK) {
NSLog(@"Failed to open database!");
}
}
return self;
}

最佳答案

copyDatabaseIfNeeded 如果不是第一次复制,会将你的资源数据库复制到应用目录文件夹

+ (void) copyDatabaseIfNeeded {

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {

NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"db.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];

if (!success)
NSAssert1(0, @"Failed to create writable database file with message \"%@\".", [error localizedDescription]);
}
}

//你的数据库在应用程序文档目录中的保存路径

 + (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"db.sqlite"];
}

关于ios - 如果 iOS sqlite 中不存在数据库,则导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23902497/

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