0

I have a NavigationView that calls out to a NavigationLink with a header record, and should then display the header information and the detail information. But when I call my FetchRequests for the details, I get Cannot use instance member 'header' within property initializer; property initializers run before 'self' is available - Here's the relevant code:

struct ViewDetailsView: View {
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(
        entity: Detail.entity(),
        sortDescriptors: [NSSortDescriptor(keyPath: \Detail.description, ascending: true)],
        predicate: NSPredicate(format: "%K == %@", #keyPath(Detail.header), header)
    ) private var details: FetchedResults<Event>    
    var header: Header
    var body: some View {
        VStack{
            Text("\(header.firstName ?? "no first name") \(header.lastName ?? "no last name")")
                .padding()
            List {
                ForEach(details) {
                    detail in
                    Text("\(detail.description ?? "Unknown description")")
                }
            }
        }
    }
}
 

I am calling this view via a NavigationLink in the Headers view:

NavigationView {
    List {
        ForEach(headers) {
            header in
            NavigationLink(destination: ViewDetailsView(header: header)) {
                Text("\(header.firstName ?? "no first name") \(header.lastName ?? "no last name")") 
// ADD @FETCHREQUEST for DETAIlS here and pass to ViewDetailsView?
            }
        }
        .onDelete(perform: deleteHeader)
    }
}

I tried to add the details fetch in the above (where the comment is) and I ended up getting the same error as the 1st view (1st code segment above). How do you correctly handle the Header / Details challenge in SwiftUI using CoreData, so that you don't load all the detail records on the Header list (NavigationView), until you actually need them in the Details View

Michael Rowe
  • 870
  • 2
  • 11
  • 27
  • 1
    You need to pass header in init and initialize fetch request programmatically like in https://stackoverflow.com/a/59451047/12299030, also next can be helpful https://stackoverflow.com/a/59345830/12299030. – Asperi Dec 31 '20 at 18:10

1 Answers1

0

Thank you @Asperi - This was the help I was looking for.. Here's how it was solved in the details view -

    init(header: Header) {
        self.header = header
        let request: NSFetchRequest<Details> = Details.fetchRequest()
        request.sortDescriptors = [NSSortDescriptor(keyPath: \Details.eventDate, ascending: true), NSSortDescriptor(keyPath: \Details.event, ascending: true)]
        request.predicate =  NSPredicate(format: "%K == %@", #keyPath(Details.header), header)
        
        _events = FetchRequest<Event>(fetchRequest: request)
    }
Michael Rowe
  • 870
  • 2
  • 11
  • 27