我能够通过 iCloud 在我的项目中的两个设备之间可靠地回显 Core Data 更改。但是我到了需要访问更改历史记录的地步。Apple 在消费相关商店更改中很好地描述了设置它的步骤
我跟着并愉快地将相关代码复制并粘贴到我的应用程序中。但是 NSPersistentStoreRemoteChange 通知没有通过。就像喜剧一样,时机就是一切。根据persistentStoreDescriptions I的文档
如果要配置自定义持久存储描述,则必须在调用 loadPersistentStores(completionHandler:) 之前设置此属性
我在loadPersistentStores(completionHandler:) 中配置了 persistentStoreDescriptions,所以最明显的方法是在 AppDelegate 中设置以下代码。
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentCloudKitContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentCloudKitContainer(name: "yourProjectNameGoesHere")
// turn on persistent history tracking
// https://developer.apple.com/documentation/coredata/consuming_relevant_store_changes
let description = container.persistentStoreDescriptions.first
description?.setOption(true as NSNumber,
forKey: NSPersistentHistoryTrackingKey)
// turn on remote change notifications
let remoteChangeKey = "NSPersistentStoreRemoteChangeNotificationOptionKey"
description?.setOption(true as NSNumber,
forKey: remoteChangeKey)
// this will make background updates from iCloud available to the context.
container.viewContext.automaticallyMergesChangesFromParent = true
// call this LAST, after the persistentStoreDescriptions configuration.
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
从您的视图控制器或模型中捕获通知。
init() {
NotificationCenter.default.addObserver(self,
selector: #selector(fetchChanges),
name: .NSPersistentStoreRemoteChange,
object: pc.persistentStoreCoordinator)
}
@objc func fetchChanges(note: Notification) {
print("Just received a NSPersistentStoreRemoteChange notification")
}