iphone - 如何在应用程序更新时保留现有数据库?

标签 iphone

我有一个 iPhone 应用程序,它使用 Sqlite 数据库来存储一些数据和一些用户配置。我遇到的问题是,当我提交应用程序的更新时,用户安装上的现有数据库将被空数据库覆盖,并且用户丢失了其配置。我确信避免这种情况不会太困难,但我不知道该怎么做。

这是我创建数据库副本的方法的代码:

// Creates a writable copy of the bundled default database in the application Documents directory.
- (void)createEditableCopyOfDatabaseIfNeeded {
    // First, test for existence.
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSString *writableDBPath = [self databasePath];
    success = [fileManager fileExistsAtPath:writableDBPath];
    if (!success) {
        // The writable database does not exist, so copy the default to the appropriate location.
        //NSLog(dbName);
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbName];
        success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
        if (!success) {
            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
        }
    }
}

这个方法称为表单:

- (BOOL)openDatabase {
    BOOL success = true;
    if (!database) {
        [self createEditableCopyOfDatabaseIfNeeded];
        if (sqlite3_open([[self databasePath] UTF8String], &database) != SQLITE_OK) {
            success = false;
            // Even though the open failed, call close to properly clean up resources.
            sqlite3_close(database);
            NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
        }
    }
    return success;
}


- (NSString*)databasePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:dbName];
    return path;
}

也许我忘记了代码中的某些内容?

有人可以帮我解决这个问题吗?谢谢你!

最佳答案

如何将 sqlite 数据库从主包复制到应用程序的文档目录,但前提是该数据库尚不存在?

关于iphone - 如何在应用程序更新时保留现有数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4157222/

相关文章:

ios - 删除UITableViewCell的最后一个分隔符

ios - 将 NSDictionary 转换为 NSArray

iphone - 更改 rootviewcontroller +[NSNotificationCenter dictationViewClass] 后出错

iphone - 将数据从我的详细 View 发送回我的 UITableView

ios - 每次从 TestFlight 首次启动时应用程序崩溃

iphone - 以编程方式更改 UITextField 的占位符文本颜色

iphone - 我可以从 iOS 模拟器中访问 App Store 吗?

objective-c - 当 URL 为空时 dataWithContentsOfURL 返回值不为 nil

iphone - 如何在 MapKit 中停止 pin 与 map 一起移动

iphone - 将“设置首选项”的“键盘类型”更改为带小数点的数字键盘