ios - Xcode核心数据: Change existing XML to Sqlite (NSXMLStoreType to NSSQLiteStoreType)

标签 ios xcode macos sqlite core-data-migration

在我的第一个应用程序中,我在持久存储协调器中使用了 NSXMLStoreType。

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

现在,我想更改为 NSSQLiteStoreType:

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

如果我只是更改商店类型,应用程序就会崩溃。那么我必须做什么呢?我可以做一次吗:

  • 检查旧商店是否存在并且
  • 如果是,将其转换为 sqlite 并
  • 之后删除旧的 xml 存储吗?

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

EDIT & ANSWER

我使用此解决方案迁移一次数据库(感谢 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];
            }
        }

最佳答案

您可以按照 Apples Core Data documentation 中所述使用 migratePersistentStore:toURL:options:withType:error: .

如果这应该自动发生,您将需要在启动时添加迁移。

关于ios - Xcode核心数据: Change existing XML to Sqlite (NSXMLStoreType to NSSQLiteStoreType),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21566819/

相关文章:

ios - Storyboard需要更多时间来加载

ios - 从特定时间开始嵌入 youtube 视频

Swift 如何在 macOS 中编辑 .mp3 文件的元数据 (ID3)

macos - NSSharingService 在消息编辑器中填充 "To:"字段

ios - 以编程方式发送 Firebase 通知? objective-c

iphone - 哪种声音格式最适合cocos2d游戏项目?

c# - 如何在 Xamarin 中动态添加 UI 元素(如 "picker")到 View ?

ios - 分组静态表后台问题

macos - 使用 Qt 框架在 MAC 上部署 Qt 应用程序

c# - 当我更改 Iphone 型号时,UIView Table Row 正在拉伸(stretch)