0

I have a SwiftUI app with CoreData+CloudKit integrated. My data model is as follows:

  • MainElement <->> SubElement <-> SubElementMetadata
    Each MainElement has one or more SubElements and each SubElement has exactly one SubElementMetadata.

Now I have a SwiftUI view to display the list of SubElements of a MainElement:

struct SubElementListView: View {
    
    @ObservedObject private var mainElement: MainElement
    
    init(mainElement: MainElement) {
        self.mainElement = mainElement
    }
    
    var body: some View {
        List(mainElement.subElements, id: \.self.objectID) { subElement in
            VStack {
                Text(subElement.title)
                Text(subElement.elementMetadata.creationDateString)
            }
        }
    }
}

The Issue:

When I update creationDateString of a SubElement somewhere in my code, the view updates to reflect the change. If, however, a change arrives over CloudKit, the view does not update.
If I navigate out and back into the view, the new data is displayed, but not while I stay on this view.

Why is this? I am aware I can probably trigger an update manually (e.g. by listening to CloudKit notifications), but I would like to understand why it doesn't "just work" - which is what I would have expected since NSManagedObject is also an ObservableObject.

BlackWolf
  • 5,239
  • 5
  • 33
  • 60
  • Too little code but you are likely not observing the store appropriately and/or not adopting changes automatically. – lorem ipsum Feb 07 '22 at 22:16
  • I'll gladly provide more code, but what other code would you need, I think that is all the relevant code, isn't it? How does the store need to be observed beyond `@ObservedObject`, which should take care of observing for changes from my understanding? Just to be clear, the changes from CloudKit ARE applied - like I said, navigating out and back into the view will update everything properly. It's just that it isn't updated automatically while I stay on this view. – BlackWolf Feb 07 '22 at 22:47
  • With @FetchRequest or NSFetchedResultsController. NSFetchRequest is a one time pull. The automatically merging of contexts between devices is set when losing the store. CoreData setup is important make sure you have followed all the required steps per documentation. Without a [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) it is impossible to help you troubleshoot. Create a same app in a clean project with as little code as possible. But there are many questions in SO about this. Plus you aren’t observing the sub elements they need a wrapper too. – lorem ipsum Feb 07 '22 at 22:53
  • In the `PersistenceController` (that the Xcode template provides) at the end of `init(inMemory: Bool = false)` add: `container.viewContext.automaticallyMergesChangesFromParent = true` – ChrisR Feb 08 '22 at 07:06

0 Answers0