Undo support for SwiftUI app with CoreData

I didn’t find an official documentation on how to setup UndoManager for CoreData in SwiftUI. Here’s how I did it (soon available in Leviathan) for iOS and macOS.

Insert managedObjectContext into the window as usual (no need to setup UndoManager here):

@main
struct LeviathanApp: App {
	    
    var moc: NSManagedObjectContext = {
        let viewContext = PersistenceController.shared.container.viewContext
	return viewContext
    }()
	
    var body: some Scene {
        WindowGroup {
	    LeviathanWindow()
                .environment(\.managedObjectContext, moc)
        }
    }
}

In the window, set the environment’s undoManager as the managedObjectContext’s undoManager. I have seen it not work when set in onAppear. Settings it in onChange(of: initial:true) works for me:

struct LeviathanWindow: View {
	
    @Environment(\.managedObjectContext) private var moc
    @Environment(\.undoManager) var undoManager

    var body: some View {
	NavigationContainer()
	    .onChange(of: undoManager, initial: true) { old, new in
		moc.undoManager = new
	    }
    }
}