In a SwiftUI Mac App with CoreData I want to use a second WindowGroup, to present CoreData NSManagedObjects from a List in the primary WindowGroup.
The for parameter of the second WindowGroup("Detail Window", for: ????) shall be a Codable & Hashable Type.
I need to transfer a CoreData Managed Object Item.
@main
struct MyApp: App {
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
ListView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
WindowGroup("Detail Window", for: Item.self) { $item in // does not compile
CreateEditView(item: item!, mode: .edit)
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
Window("Single Window", id: "sw") {
SingleWindowView()
}
}
}
does not compile, because Item does not conform to the required protocols. What type can I use?
Can I work with an ID instead, as advised in the WWDC 2022 Video "Bringing multiple Windows to your SwiftUI App".
What can I use as ID for an CoreData ManagedObject.
CodePudding user response:
You can easily conform your NSManagedObject to Identifiable
and use the objectID
property as the unique id since it is always unique.
One problem is that the id type doesn't conform to Codable
but that can be resolved by converting it to an URL
.
extension Item: Identifiable {
public var id: URL {
self.objectID.uriRepresentation()
}
}
And the window group is then declared as
WindowGroup(for: Item.ID.self) { $id in