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

时间:2014-10-12 12:16:21

标签: ios sqlite

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

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

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

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

1 个答案:

答案 0 :(得分:2)

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

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

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

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

    • 如果没有,请将其从包中复制到Documents;

    • 只有这样,您才可以尝试从Documents打开数据库(但不能从捆绑包中打开)。

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

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

    - (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);
                }
            }
        }
    }