swift - 使用 SwiftUI 和 Core Data 镜像 CloudKit 进行屏幕更新
问题描述
当通过 cloudkit 同步新信息时,我在获取更新视图时遇到问题。在两台设备上运行此应用时,如果设备 A 添加调色板,则仅在应用重新启动时才会出现在设备 B 上。我已经查看了有关堆栈溢出的其他一些答案,但没有一个有效。有人有什么主意吗?
这是我来自 AppDeligate 的持久容器
lazy var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "Swatch")
// get the store description
guard let description = container.persistentStoreDescriptions.first else {
fatalError("Could not retrieve a persistent store description.")
}
// initialize the CloudKit schema
let id = "iCloud.com.peterfoxflick.swatch"
let options = NSPersistentCloudKitContainerOptions(containerIdentifier: id)
description.cloudKitContainerOptions = options
let remoteChangeKey = "NSPersistentStoreRemoteChangeNotificationOptionKey"
description.setOption(true as NSNumber,
forKey: remoteChangeKey)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
container.viewContext.automaticallyMergesChangesFromParent = true
return container
}()
而我的看法
struct PalettesListView: View {
@EnvironmentObject var palettesList: PalettesListViewModel
let pub = NotificationCenter.default
.publisher(for: NSNotification.Name("NSPersistentStoreRemoteChangeNotificationOptionKey"))
var body: some View {
NavigationView {
List{
ForEach(self.palettesList.palettes){ p in
Text(p.name)
.font(.headline)
}
}
}
.onReceive(pub) { (output) in
self.palettesList.fetch()
}
}
struct SwatchesListView_Previews: PreviewProvider {
static var previews: some View {
PalettesListView()
}
}
我也尝试将相同的侦听器添加到我的 ViewModel 但没有运气。如果您想查看所有代码,可以查看 GitHub。
PS。某些括号/格式可能已关闭,我将代码缩减为相关部分。
解决方案
你的合并策略是让本地更改胜过远程更改。尝试删除它或使用不同的合并策略。
推荐阅读
- sql - 将 WHERE 子句添加到查询会减慢查询速度 - 即使列已编入索引
- r - 有没有办法从 effect_plot 中删除网格线?
- sql-server - SQL 更新所有行 NO WHERE 语句 VB.net
- docker - 大厅:在放置步骤期间无法访问作业资源
- javascript - 如何过滤嵌套数组(组成JS过滤器)
- c - 如何在c中通过串口连接编写二进制表示
- python - 如何在熊猫数据框列中查找累积产品
- python - 将零设置为第一行包含 1 的那些列
- c - Json_setValue() 函数中只有一半的字符串值设置为键
- python - 如何对单张图像进行预处理和预测