iphone - 无法将 sqlite 数据库从应用程序的主包复制到用户文档

标签 iphone ios database sqlite ios-simulator

我无法将我的 sqlite 数据库复制到用户文档文件夹,数据库始终为 0 字节但应该有 322 kb。

我还检查了数据库是否包含在目标成员中。

问题是我无法正确复制数据库。

这是我的代码:

-(void)initDatabase
{
// Create a string containing the full path to the sqlite.db inside the documents folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:@"wine.sqlite"];

// Check to see if the database file already exists
bool databaseAlreadyExists = [[NSFileManager defaultManager] fileExistsAtPath:databasePath];

// Open the database and store the handle as a data member
if (sqlite3_open([databasePath UTF8String], &databaseHandle) == SQLITE_OK)
{

    // Create the database if it doesn't yet exists in the file system
    if (!databaseAlreadyExists)
    {
        // Get the path to the database in the application package
        NSString *databasePathFromApp = [[NSBundle mainBundle] pathForResource:@"wine" ofType:@"sqlite"];
        //NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"wine.sqlite"];

        // Copy the database from the package to the users filesystem
        [[NSFileManager defaultManager] copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];

        NSLog(@"Database created");
    }
}

最佳答案

有逻辑错误,你检查里面的databaseAlreadyExists

if (sqlite3_open([databasePath UTF8String], &databaseHandle) == SQLITE_OK) { ... }

阻止。

你的意思可能是

// Check to see if the database file already exists
bool databaseAlreadyExists = [[NSFileManager defaultManager] fileExistsAtPath:databasePath];

// Create the database if it doesn't yet exists in the file system
if (!databaseAlreadyExists)
{
    // Get the path to the database in the application package
    NSString *databasePathFromApp = [[NSBundle mainBundle] pathForResource:@"wine" ofType:@"sqlite"];

    // Copy the database from the package to the users filesystem
    [[NSFileManager defaultManager] copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];

    NSLog(@"Database created");
}

// Open the database and store the handle as a data member
if (sqlite3_open([databasePath UTF8String], &databaseHandle) == SQLITE_OK)
{
   ...
}

关于iphone - 无法将 sqlite 数据库从应用程序的主包复制到用户文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14113015/

相关文章:

java - 嵌入到 Java 应用程序中的简单数据库

php - 如何将一行与另一个表中的另一行连接

mysql - 规范在线购物车表

ios - 在 xcode 8 中从 swift 2.2 迁移到 swift 3.0

iphone - CSS3 简化 Mobile Safari

ios - 主菜单不适用于 iO

ios - 为什么 MKTileOverlay 在 ios、swift4 中为 openstreet map 一遍又一遍地重复相同的图 block

iphone - 使用音频队列处理中断

iphone - 带按钮的自定义 UINavigationController

iphone - 启动远程程序时出错 : failed to get the task for process 3595