【问题标题】:why is there no data in my sqlite file when it is installed on iOS app?为什么我的 sqlite 文件安装在 iOS 应用程序上时没有数据?
【发布时间】:2014-10-12 12:16:20
【问题描述】:

为什么我的sqlite文件安装在iOS应用上时没有数据?

问题是应用在尝试从数据库中读取数据时无法看到文件/数据库中的任何数据(它不存在)。

我有一个我正在使用的 sqlite 文件,它被添加到 Xcode 中的项目中。如果我使用 sql 编辑器连接到文件/数据库,我会看到我的数据。然后我运行我的应用程序并使用相同的编辑器在模拟器上读取文件并且没有数据。没有表或行,但文件名相同。

我没有做任何特别的事情来将它复制到应用程序或离线文件夹或任何东西。看起来它会进入 Documents 文件夹(这似乎是默认的,不知道如何更改或是否需要)。

【问题讨论】:

  • 我认为问题在于您没有任何代码。也许与没有搜索到任何适用于 iOS 的 SQLite 设置代码的优秀示例的问题相结合。

标签: ios sqlite


【解决方案1】:

您应该从 Documents 文件夹中打开数据库,但您必须让打开的例程自己将其复制到那里。

  1. 确认数据库包含在包中。转到“目标设置”,单击“构建阶段”选项卡,然后查看“复制捆绑资源”列表。确保您的数据库包含在其中,如果还没有,请添加它。

  2. 您的数据库打开例程应该:

    • 在 Documents 中查找数据库是否存在(使用NSFileManager);

    • 如果没有,则将其从捆绑包复制到 Documents;

    • 只有这样,您才能尝试从 Documents(但不能从 bundle)打开数据库。

    注意,如果您在完成上述三点之前尝试从 Documents 打开数据库,sqlite3_open 命令将在找不到时创建一个空白数据库。因此,您可能需要确保在尝试上述操作之前删除所有空白数据库。最简单的方法是从设备/模拟器中删除应用程序,然后再次运行。

因此,您可能有这样的例程:

- (void) installDatabaseIfNeeded {

    // Get the documents database path

    NSString *documentsFolder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *documentsDatabasePath = [documentsFolder stringByAppendingPathComponent:@"test.sqlite"]; // always use setter when setting property's value

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:documentsDatabasePath]) {

        // if the database doesn't exist in documents, look for it in the bundle and copy it if found

        NSString *bundleDatabasePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"sqlite"];

        if (bundleDatabasePath) {
            NSError *error;
            if (![fileManager copyItemAtPath:bundleDatabasePath toPath:documentsDatabasePath error:&error]) {
                NSLog(@"copyItemAtPath failed: %@", error);
            }
        }
    }
}

【讨论】:

  • 我没想到如果文件不存在,sqlite 只会制作文件。这就是一定发生的事情。谢谢
猜你喜欢
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
  • 2017-07-02
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 2014-01-09
  • 1970-01-01
相关资源
最近更新 更多