【问题标题】:Sqlite3 from Bundle Resources in iOS来自 iOS 捆绑资源的 Sqlite3
【发布时间】:2014-06-07 19:53:53
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 您想在哪里添加您的 .db 文件?在文档目录中?
  • 在对 DB 进行任何操作之前,您需要将其复制到文档文件夹中。
  • 你应该把它复制到文档目录来插入、删除或更新数据,因为你不能从 mainbundle 访问目录
  • 查看我对此link 的回答。这将copy your database into document directory file from your bundle。然后你可以使用这个数据库并插入、更新、删除你的数据。

标签: ios sqlite resources nsbundle


【解决方案1】:

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

 }

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

【讨论】:

    【解决方案2】:

    您需要将该项目文件添加到文档目录中,

    你可以这样做,

    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *sourcePath = [[[NSBundle mainBundle] bundlePath]stringByAppendingPathComponent:@"networks.db"];
    
    NSError *error;
    
    [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:documentsDirectory error:&error];
    

    如果你想对 SQLite3 文件做任何事情,你可以使用任何 SQLite 管理器,例如SQLite Manager

    【讨论】:

      【解决方案3】:

      查看我对此link 的回答。 这将copy your database into document directory file from your bundle。然后你就可以使用这个数据库插入、更新、删除你的数据了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-15
        • 2016-04-01
        • 1970-01-01
        • 2015-11-24
        • 2021-05-08
        • 1970-01-01
        • 2016-08-02
        相关资源
        最近更新 更多