ios - iOS 中捆绑资源中的 Sqlite3

标签 ios sqlite resources nsbundle

您好,我计划从我的项目资源文件夹中添加静态 SQLite3,但我不知道我是否正确执行了操作。

到目前为止,这是我的进展... 从 SQLite Database Browser 创建 SQLite3 数据库

将 Sqlite3 数据库复制到我的项目文件夹 enter image description here

将network.db添加到我的项目资源文件夹中 enter image description here

现在我不知道下一步该去哪里..我希望有人能帮助我解决我的问题。

最佳答案

如果您在运行时修改数据库(即插入、删除或更新记录),则需要创建从包到文档目录的副本。 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/

相关文章:

iphone - iOS 的 HTTP 中的 getReasonPhrase()

ios - 无法从文件路径创建 UIImage

sqlite - 无法加载文件或程序集 SQLitePCLRaw.core

design-patterns - 有没有好的设计模式食谱/食谱资源?

c - 在这个例子中应该创建什么任务?

java - 如果关闭资源失败,java 会做什么?

ios - 在主线程上分派(dispatch) NSNotification 或在主线程上传递通知哪个更好

ios - cellForRowAtIndexPath中的NSRangeException

iPhone Sqlite 性能问题

c++ - 在存储到 sqlite 上的记录时处理字符串中的特殊字符