iOS 中捆绑资源中的 Sqlite3 [英] Sqlite3 from Bundle Resources in iOS

查看:48
本文介绍了iOS 中捆绑资源中的 Sqlite3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我打算从我的项目资源文件夹中添加一个静态 SQLite3,但我不知道我的操作是否正确.

Hi I'm planning to add a static SQLite3 from my projects resource folder but I dont know if I'm doing it correctly.

到目前为止,这是我的进步......从 SQLite 数据库浏览器

so far here's my progress... Created SQLite3 Database from SQLite Database Browser

复制 Sqlite3 数据库到我的项目文件夹

Copied Sqlite3 Database to my project folder

将 network.db 添加到我的项目资源文件夹

Added network.db to my project resource folder

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

and now I don't know where to go next.. I hope someone can help me with my problem.

推荐答案

如果您在运行时修改数据库(即插入、删除或更新记录),您需要创建一个从包到文档目录的副本.iOS sendboxing 机制不允许您在运行时修改包资源.因此,您需要将其复制到文档目录.下面的代码可以帮助你:

If you are modifying your database at run time (i.e. you are inserting, deleting or updating records), you need to create a copy from bundle to documents directory. iOS sendboxing mechanism will not allow you to modify bundle resource at run time. So, you need to copy it to documents directory. Below code can help you out:

 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]);

 }

如果您仅将数据库用于查找目的(仅用于选择查询),则无需从包复制到文档目录.

If you are referring your db for lookup purpose only (only using it for select queries), there is no need to copy from bundle to documents directory.

这篇关于iOS 中捆绑资源中的 Sqlite3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆