Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

ios - Correct way of handling Header / Detail views in CoreData with SwiftUI

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...