我刚刚添加了一个选项,让用户在我的应用程序中切换云同步,我保存用户是否想在“useCloudSync”下的 UserDefaults 中使用 iCloud 同步。当应用程序运行时,我加载了我的 persistentContainer:
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 加载数据时更改容器。
NSPersistentCloudKitContainer
当用户切换“CloudSync”时,我该如何更改?