没那么复杂。创建视图时,您已经在 sceneDelegate 中有一个上下文。只需执行获取。
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let fetchRequest: NSFetchRequest<YourEntity> = YourEntity.fetchRequest()
fetchRequest.sortDescriptors = []
//fetchRequest.predicate = //some filters
let result = try? context.fetch(fetchRequest)//it always returns an array but it may be empty. Fetch may throw if disc is unavailable or some other reasons
//do what you need
let contentView = ContentView().environment(\.managedObjectContext, context)
通常,您可以将 UUID 存储为对象版本。每次在后端修改对象时,都可以使用新的 UUID 更新版本。因此,您只需要检查版本 - 如果不同,您需要更新对象。但它仅在用户无法离线修改对象的情况下。如果可以的话,一定有一些复杂的碰撞解决逻辑。