I'm trying to build a SwiftUI view with data from Core Data. One of the entities has a one-to-many relationship with another entity. I have a basic master detail type with a NavigationLink to a second view which should be the equivalent of a detail view. I can in fact list all of the details for the second entity except for the Set of related objects.
Relevant entities:
public class Regimen : NSManagedObject, Identifiable {
@NSManaged public var id: UUID
@NSManaged public var name: String?
//...more
@NSManaged public var drugObjects: Set<DrugObject>
}
public class DrugObject : NSManagedObject, Identifiable {
@NSManaged public var id: UUID
@NSManaged public var name: String?
//...more
@NSManaged public var regimen: Regimen
}
The master list:
struct RegimenListView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(fetchRequest: Regimen.getAllRegimens()) var myRegimens
var body: some View {
NavigationView {
List {
ForEach(myRegimens, id: \.self) { mr in
NavigationLink(destination: RegimenDetailView(regimen: mr)) {
Text(mr.name ?? "no regimen name")
}
}
}.navigationBarTitle("Regimens")
}
}
}
The detail list:
struct RegimenDetailView: View {
var regimen: Regimen
var body: some View {
//let da: [DrugObject] = Array(regimen.drugObjects)
return NavigationView {
VStack {
Text(regimen.name ?? "no regimen name")
List {
ForEach(regimen.drugObjects, id: \.self) { x in
Text(x.name ?? "no drugObject name")
}
}
}
}
}
}
If I try to build as listed above, I get an error on the ForEach line: Generic struct 'ForEach' requires that 'Set' conform to 'RandomAccessCollection'
If I first try to convert to an Array, it blows up with the error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MyChems.DrugObject copyWithZone:]: unrecognized selector sent to instance '
Any guidance would be appreciated. Xcode 11.6 iOS 13.6