SwiftUI not updating Core Data after change?

I've got a core data model, with a name, which I've cleverly called cdName. My view has:

    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(sortDescriptors: [
        SortDescriptor(\Item.cdName),
    ])
    private var items: FetchedResults<Item>

and then, later

                ForEach(self.items, id: \.self) { item in
                    NavigationLink {
                        ItemView(item: item)
                            .environment(\.managedObjectContext, self.viewContext)
                    } label: {
                        LabelWithMenuView(label: item.cdName ?? "<no name>") { ptr in
                            if let newName = ptr {
                                let oldName = item.cdName!
                                item.cdName = newName
                                do {
                                    try self.viewContext.save()
                                } catch {
                                    print("Could not save rename of \(oldName) to \(newName)")
                                }
                        }

(LabelWithMenuView is a view that has an on-hover button which brings up a rename sheet and passes the new name off to the completion handler.)

When I do this (macOS)... it does change the name in Core Data, but it doesn't update the view. If I quit&restart my app, it shows up with the new name.

What am I doing wrong, please?

  • you do have item marked as an @ObservedObject in the ItemView, yes ?

  • Ooooh, let me try that. <pause> Nope, it had been an @State in the ItemView, I changed it to @ObservedObject, and it still doesn't update the view.

Add a Comment

Replies

Solved: my LabelWithMenuView takes a String, and the surrounding view doesn't care that the object changed, so I instead changed it to pass in the object, which is then an ObservedObject, and the rename works properly. This is very strange to me, since the rename actually happens in surrounding view.