sqlite3数据库奇怪地从NSDocumentDirectory中消失

时间:2015-01-30 19:40:18

标签: objective-c sqlite nsdocumentdirectory

问题:经过长时间运行没有问题,我的数据库让我头疼,它只是不会留在NSDocumentDirectory中的位置。数据库奇怪地消失了。

我从不清除文件夹或删除任何内容。它只包含数据库并保存一些图像,如果用户想保留它们,可以下载它们。

有人知道会发生什么事吗?

经过3天的努力解决这个问题后,我无法找到可能的解决方案,所以请帮助我! :(

在我的Database-Singleton中我有以下init-Method

- (id)initWithName{
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];

    databasePath = [documentsDir stringByAppendingPathComponent:kDatabaseName];
    //kDatabaseName = nameOfDatabase.db
    [self checkAndCreateDatabase];
    return self;
}

和checkAndCreateDatabase - 方法:

- (void) checkAndCreateDatabase{
    // Check if the SQL database has already been saved to the users phone, if not then copy it over
    BOOL success;

    // Create a FileManager object, we will use this to check the status
    // of the database and to copy it over if required
    NSFileManager *fileManager = [NSFileManager defaultManager];

    // Check if the database has already been created in the users filesystem
    NSURL *urlpath = [NSURL fileURLWithPath:databasePath];
    NSError *error = nil;
    [urlpath setResourceValue: [NSNumber numberWithBool: YES]
                       forKey: NSURLIsExcludedFromBackupKey error: &error];
    success = [fileManager fileExistsAtPath:databasePath];

    // If the database already exists then return without doing anything
    if(success && sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
    {
        NSLog(@"database opened");
        sqlite3_close(database);
        return;
    }
    else{
        sqlite3_close(database);
        NSLog(@"Database was created");
    }

    // If not then proceed to copy the database from the application to the users filesystem

    // Get the path to the database in the application package
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
    //NSString *databasePathFromApp = [[NSBundle mainBundle] pathForResource:databaseName ofType:@"sqlite3"];

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

    if ([self createTables]){ //creates tables of DB, works fine
        NSLog(@"Tables were created");    
    } else {
        NSLog(@"Database failed to create and open");
    }
}

这段代码连续工作了一年。突然间,当我需要做一些更新时,数据库不再保存了。 经过大量的故障排除后,我发现数据库正在Documents文件夹中创建,但是当我尝试访问完全相同的路径时(因为我没有触及变量)它会消失,它的表格就会消失

我尝试了不同版本的存储库,所有这些版本似乎都有问题。我真的生气了。 :(

1 个答案:

答案 0 :(得分:1)

您是否在应用启动之间持续databasePath?在iOS 8中,DocumentsDirectory(以及所有其他的,Caches,tmp等)变得动态 - 他们的名字在每个应用程序启动之间发生变化。因此,如果您在应用程序中的任何位置存储绝对路径,则下次应用程序启动时它将无效。如果是这种情况,修复它的一个好方法是存储相对于DocumentsDirectory的路径,并在需要时调用

NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

并追加你的路径。

帮助这有帮助。