Core Data master view updates detail view but not vice versa

In my app I have a master `ContentView` which uses a `FetchRequest` in order to grab entities:


    struct ContentView: View {
        @Environment(\.managedObjectContext) var managedObjectContext
        @FetchRequest(
            entity: Note.entity(),
            sortDescriptors: [
                NSSortDescriptor(key: "title", ascending: true, selector: #selector(NSString.caseInsensitiveCompare))
            ]
        ) var notes: FetchedResults


Then I spit them out in a loop like so:



    NavigationView {
        List {
            ForEach(notes, id: \.self) {note in
                NavigationLink(destination: NoteDetailView(note: note), label: {


In my `NoteDetailView`, I use the `note` to display its details:


    struct NoteDetailView: View {
        var note: Note


I also have another view which handles editing the `Note`:


    struct EditNoteView: View {
        var note: Note
        @Environment(\.managedObjectContext) var managedObjectContext
        @State var noteTitle: String = ""
        @State var noteType: String = "Note"
        @State var noteColor: String = "None"


This `EditNoteView` will make changes to a `Note` then save it:


    func saveNote() {
        noteTitle = noteTitle.trimmingCharacters(in: .whitespacesAndNewlines)
       
        if (noteTitle.count > 0) {
            note.title = noteTitle
            note.type = noteType
            note.color = noteColor
            note.dateUpdated = Date()
           
            do {
                try managedObjectContext.save()
            } catch {
                print(error)
            }
        }
    }


The user can open this `EditDetailView` from either the master view (`ContentView`) or the detail view (`NoteDetailView`).


Now I've read up on this and it appears I have the opposite problem of some other people. Most people seem to have a problem updating the master from the detail view. When I call `EditNoteView` from the `NoteDetailView` and make changes it updates both the `ContentView` and then `NoteDetailView` with the changes perfectly.


However, when I call `EditNoteView` from the `ContentView` and make changes it only updates the `ContentView` and not the `NoteDetailView`.


I should mention that this is a catalyst app and I only notice this problem on devices that show the master view as a sidebar (Mac & iPad). I'm guessing it is because when I am making edits from the master view, the detail view is not "active" and therefore it doesn't think it needs to update? I'm not sure how to fix this.

Replies

A quick off-the-cuff suggestion: use an @ObservedObject wrapper on the note property in your detail view. That lets SwiftUI see that you're using it, so it will monitor it for changes and refresh the view when those changes happen.


struct NoteDetailView: View {
    @ObservedObject var note: Note
    ...
}