Xcode - 在Library文件夹中保存sqlite3数据库

时间:2012-08-22 05:49:10

标签: objective-c ios xcode sqlite bundle

我正在开发一个使用Sqlite3数据库的应用程序。目前,db是在应用程序包内部,但我知道当我在现实世界中使用真正的iPhone进行测试时,我将无法更新数据。

1 - 如何在捆绑阶段将我的项目数据库复制到Library文件夹?

2 - 如何访问此复制的数据库?现在我的代码是:

NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"myDatabase.sqlite"];
    BOOL success = [fileMgr fileExistsAtPath:dbPath];

我需要改变什么?

3 - 如果我更新应用程序,如何保留此数据库(包含用户的数据)?

提前致谢! ;)

1 个答案:

答案 0 :(得分:1)

您必须将数据库从Resources文件夹复制到Documents文件夹

sqlite3 *database;
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Lists.db"];
success = [fileManager fileExistsAtPath:writableDBPath];
// The writable database does not exist, so copy the default to the appropriate location.
if(!success)
{
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Lists.db"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        TFLog(@"Failed moving database... %@",[error localizedDescription]);
        return;
    }
}

当您在Documents文件夹中更新您的应用程序数据库时,他们只需要检查条件

     success = [fileManager fileExistsAtPath:writableDBPath];
if it does not exits new database will be copied their.
Just keep in mind database structure is same as before.