如何将核心数据的数据迁移到应用组的数据

I just added App Groups to my app using this StackOverFlow post. Unfortunately since the defaultDirectoryURL is changing, I can not fetch any of the old data I made before using the App Groups directory. I know the data is still there because when I switch back to using a regular NSPersistentContainer instead of the GroupedPersistentContainer, I can get the data.

如何将旧数据迁移到获取应用程序组数据的位置?

核心数据代码:

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
   }
}

分组的PersistentContainer代码:

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!
    }
}

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

评论
心痛算什么
心痛算什么
import UIKit
import CoreData

class GroupedPersistentContainer: NSPersistentContainer {

    override open class func defaultDirectoryURL() -> URL {
        var storeURL = FileManager.default
            .containerURL(forSecurityApplicationGroupIdentifier: "group.YourApp")
            .unsafelyUnwrapped

        storeURL = storeURL.appendingPathComponent("YourApp.sqlite")
        return storeURL
    }
}

See also: Sharing data using Core Data: iOS App and Extension

点赞
评论