您好,我计划从我的项目资源文件夹中添加静态 SQLite3,但我不知道我是否正确执行了操作。
到目前为止,这是我的进展... 从 SQLite Database Browser 创建 SQLite3 数据库
将 Sqlite3 数据库复制到我的项目文件夹
将network.db添加到我的项目资源文件夹中
现在我不知道下一步该去哪里..我希望有人能帮助我解决我的问题。
最佳答案
如果您在运行时修改数据库(即插入、删除或更新记录),则需要创建从包到文档目录的副本。 iOS sendboxing 机制不允许您在运行时修改捆绑资源。因此,您需要将其复制到文档目录中。下面的代码可以帮助您:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *filePath = [documentsDir stringByAppendingPathComponent:@"network.db"];
BOOL success = [fileManager fileExistsAtPath:filePath];
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] pathForResource:@"network" ofType:@"db"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:filePath error:&error];
if (!success)
NSAssert1(0, @"Failed to create writable resource file with message '%@'.", [error localizedDescription]);
}
如果您引用数据库仅用于查找目的(仅将其用于选择查询),则无需从 bundle 复制到文档目录。
关于ios - iOS 中捆绑资源中的 Sqlite3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23236554/