如何覆盖iOS中的SQLite数据库

我创build了一个应用程序,我在哪里使用SQLlite数据库…如果需要,我复制该数据库在应用程序的第一次启动NSCaches目录中使用以下方法:

- (void) copyDatabaseIfNeeded { //Using NSFileManager we can perform many file system operations. NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error; NSString *dbPath = [self getDBPath]; BOOL success = [fileManager fileExistsAtPath:dbPath]; if(!success) { NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"datenbankSpeed"]; success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error]; if (!success) NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); } } - (NSString *) getDBPath { //Search for standard documents using NSSearchPathForDirectoriesInDomains //First Param = Searching the documents directory //Second Param = Searching the Users directory and not the System //Expand any tildes and identify home directories. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory , NSUserDomainMask, YES); NSString *documentsDir = [paths lastObject]; return [documentsDir stringByAppendingPathComponent:@"datenbankSpeed"]; } 

我的问题是,如果我在数据库文件中更改了某些内容,并为我的客户创build了一个新的应用程序文件,他们会在旧应用程序上安装新的应用程序,但是旧数据库仍在使用中,这将导致崩溃!

我假设只有当你改变你的数据库模式的问题。 在sqlite数据库中创build一个版本表,并添加一个列schema_version ,并用代码中的值填充它。 现在,每当你改变你的sql模式,更新代码中的schema_version数字。 在copyDatabaseIfNeeded ,检查是否有现有的db文件,打开它并读取schema_version 。 如果这个版本和你现在的版本是一样的,那么你没问题。 否则,您需要迁移模式。 你也可能也想把数据迁移到新的模式中。

编辑:澄清 – 在copyDatabaseIfNeeded ,执行以下操作:

 int version = ... // read schema_version from db if (version != kCurrentSchemaVersion) { // convert the schema into new version preserving data if required. // this can be a multi-step process. Eg. if user directly upgrades to schema_version 3 // after schema_version 1, first you'll convert from 1->2, then 2->3. } 

你可能也想看看@Martin在评论中提到的PRAGMA user_version