【发布时间】:2021-02-06 10:14:01
【问题描述】:
大部分 CloudKit+CoreData 教程使用 SwiftUI,它们的实现包括 @FetchRequest,它会自动检测 CoreData 获取中的变化并刷新 UI。
https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-fetchrequest-property-wrapper
如果没有 SwiftUI,我将如何实现这一目标?我希望能够控制刷新 UI 的方式,以响应检测到由于 iCloud 更新而发生的 CoreData 更改。
我有这个来设置 NSPersistentCloudKitContainer 并注册远程通知:
let storeDescription = NSPersistentStoreDescription()
storeDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
let container = NSPersistentCloudKitContainer(name: "CoreDataDemo")
container.persistentStoreDescriptions = [storeDescription]
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveCloudUpdate), name: .NSPersistentStoreRemoteChange, object: container.persistentStoreCoordinator)
但是,我不知道如何处理 .NSPersistentStoreRemoteChange,就像 SwiftUI 实现自动执行它一样。该方法被许多不同的线程非常频繁地调用(仅在启动时多次)。
【问题讨论】:
-
您在这方面取得了进展吗? @FetchRequest 似乎是反 MVVM,但我遇到了你提到的同样的问题。
-