问题
I have my SwiftUI app working with Core Data + CloudKit. I am able to save new entries to the database from my Mac or iPhone. The app uses the exact same project/codebase for all devices.
The only problem is that I need to close out of the app and re-open it to see any new entries made from the other device. I can immediately see the new entries made from the same device, but they do not appear on the other devices until I close and re-open the app on it.
Am I missing something here? Do I need to add something like ObservableObject or Identifiable to my Entity class? How do I correct this issue?
Edit:
Here is how I obtain the records:
@FetchRequest(
entity: Doc.entity(),
sortDescriptors: [NSSortDescriptor(key: "title", ascending: true)]
) var docs: FetchedResults<Doc>
回答1:
Figured it out!
I had to add:
context.automaticallyMergesChangesFromParent = true
To the scene()
function in SceneDelegate
:
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
context.automaticallyMergesChangesFromParent = true
Now its working flawlessly.
Credit: https://www.andrewcbancroft.com/blog/ios-development/data-persistence/getting-started-with-nspersistentcloudkitcontainer/
来源:https://stackoverflow.com/questions/58860967/core-data-cloudkit-not-refreshing-on-other-device-automatically