如何将Core Data的数据迁移到App Group的数据

ap1*_*123 5 migration core-data swift ios-app-group nspersistentcontainer

我刚刚App Groups使用此StackOverFlow 帖子添加到我的应用程序中。不幸的是,由于defaultDirectoryURL正在发生变化,我无法获取在使用应用程序组目录之前制作的任何旧数据。我知道数据仍然存在,因为当我切换回使用常规NSPersistentContainer而不是 时GroupedPersistentContainer,我可以获取数据。

如何将旧数据迁移到我正在获取应用组数据的位置?

核心数据代码:

class CoreDataManager {
    static let sharedManager = CoreDataManager()
    private init() {}

    lazy var persistentContainer: NSPersistentContainer = {
        var useCloudSync = UserDefaults.standard.bool(forKey: "useCloudSync")

        let containerToUse: NSPersistentContainer?
        if useCloudSync {
           containerToUse = NSPersistentCloudKitContainer(name: "App")
        } else {
            containerToUse = GroupedPersistentContainer(name: "App")
            let description = containerToUse!.persistentStoreDescriptions.first
            description?.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
      }

        guard let container = containerToUse, let description = container.persistentStoreDescriptions.first else {
            fatalError("Hey Listen! ###\(#function): Failed to retrieve a persistent store description.")
        }
        description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)

        container.loadPersistentStores(completionHandler: { (storeDescription, error) in

      ...

      return container
   }
}
Run Code Online (Sandbox Code Playgroud)

分组持久容器代码:

class GroupedPersistentContainer: NSPersistentContainer {
    enum URLStrings: String {
        case group = "group.App"
    }

    override class func defaultDirectoryURL() -> URL {
        let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: URLStrings.group.rawValue)

        if !FileManager.default.fileExists(atPath: url!.path) {
            try? FileManager.default.createDirectory(at: url!, withIntermediateDirectories: true, attributes: nil)
        }
        return url!
    }
}
Run Code Online (Sandbox Code Playgroud)

我还没有为我的 NSPersistentCloudKitContainer 执行此操作,但它将遵循与此相同的格式。