NSPersistentCloudKitContainer

NSPersistentCloudKitContainer

本文介绍了强制NSPersistentContainer更改核心数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚为用户添加了在我的应用程序中切换云同步的选项,该选项保存了用户是否要在"useCloudSync"下的UserDefaults中使用iCloud同步.当应用运行时,我会加载我的persistentContainer:

I just added the option for a user to toggle Cloud sync inside my app where I save whether or not the user wants to use iCloud sync in UserDefaults under "useCloudSync". I load my persistentContainer when the app runs with:

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 = NSPersistentContainer(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
   }
}

当用户使用UISwitcher切换云同步时,我在UserDefaults中更改了"useCloudSyc"的值,但是在强制关闭应用程序并重新运行之前,该应用程序不使用 NSPersistentCloudKitContainer 再来一次.我希望当用户切换开关以开始从iCloud加载数据时,容器会正确更改.

When a user toggles cloud sync with a UISwitcher, I change the value for "useCloudSyc" in UserDefaults, but the app doesn't use the NSPersistentCloudKitContainer until they force close the app and re-run it again. I would like the container to change right when the user toggles the switch to start loading their data from iCloud.

当用户切换"CloudSync"时,如何在 NSPersistentCloudKitContainer 之间切换?

How can I change to and from a NSPersistentCloudKitContainer when the user toggles "CloudSync"?

推荐答案

这里是可行的方法

extension UserDefaults { // helper key path for observing
    @objc dynamic var useCloudSync: Bool {
        return bool(forKey: "useCloudSync")
    }
}

class CoreDataManager {
    static let sharedManager = CoreDataManager()

    private var observer: NSKeyValueObservation?
    private init() {
    }

    lazy var persistentContainer: NSPersistentContainer = {
        setupContainer()
    }()

    private func setupContainer() -> NSPersistentContainer {

        if nil == observer {
            // setup observe for defults changed
            observer = UserDefaults.standard.observe(\.useCloudSync) { [weak self] (_, _) in
                try? self?.persistentContainer.viewContext.save() // save anything pending
                if let newContainer = self?.setupContainer() {
                    self?.persistentContainer = newContainer
                }
            }
        }

        let useCloudSync = UserDefaults.standard.bool(forKey: "useCloudSync")

        let containerToUse: NSPersistentContainer?
        if useCloudSync {
            containerToUse = NSPersistentCloudKitContainer(name: "App")
        } else {
            containerToUse = NSPersistentContainer(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 { (storeDescription, error) in
            //      ...
        }

        return container
    }
}

这篇关于强制NSPersistentContainer更改核心数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 12:47