Xcode核心数据:将现有的XML更改为Sqlite(NSXMLStoreType为NSSQLiteStoreType)

在我的第一个应用程序中,我在持久性商店协调员中使用了一个NSXMLStoreType。

[storeCooordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:storeURL options:options error:nil]; 

现在,我想更改为NSSQLiteStoreType:

 [storeCooordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:nil]; 

应用程序崩溃,如果我只是改变商店types。 那我该怎么办? 我可以做一次吗?

  • 检查旧商店是否存在
  • 如果是转换成sqlite和
  • 之后删除旧的XML存储?

我不知道如何将其转换为SQLite。 模型是一样的。

编辑&答复

我使用这个解决scheme迁移一次数据库( 感谢Volker

 //-> applicationFilesDirectory is the url to the documents directory NSURL* oldURL = [applicationFilesDirectory URLByAppendingPathComponent:@"DBName1.xml"]; NSURL* newURL = [applicationFilesDirectory URLByAppendingPathComponent:@"DBName2.sqlite"]; NSError *error = nil; NSFileManager * fileManager = [NSFileManager defaultManager]; //-> if file exists if ([fileManager fileExistsAtPath:[oldURL path]]) { NSLog(@"File is here"); NSManagedObjectModel* managedModel = [NSManagedObjectModel mergedModelFromBundles:nil]; NSPersistentStoreCoordinator* tempCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedModel]; id xmlStore = [tempCoordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:oldURL options:options error:nil]; [tempCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:newURL options:options error:nil]; if ( ![tempCoordinator migratePersistentStore:xmlStore toURL:newURL options:options withType:NSSQLiteStoreType error:&error] ) { //-> delete the old file from directory [fileManager removeItemAtURL:oldURL error:NULL]; } } 

您可以使用migratePersistentStore:toURL:options:withType:error:如Apples Core Data文档中所述 。

如果这会自动发生,则需要在启动时添加迁移。