lcj
lcj

Reputation: 1787

Dynamically filtering @FetchRequest with SwiftUI using EnvironmentObject

Is there any way to create a FetchRequest using an EnvironmentOjbect as a NSPredicate? I read this article by Paul Hudson, which is great, but I did not want to pass in the variable to the init. Instead I wanted to use an EnvrionmentObject. I tried the response starting with "Edit 9/10/2023" of this post, but it kept crashing.

I tried one of the responses in this post (the one that starts with "After two years I have the solution"), with onAppear vs onChange but it didn't seem to use the NSPredicate or refresh the data.

@EnvironmentObject var myObject: MyObject
@FetchRequest(sortDescriptors: [SortDescriptor(\.name)]) var scenarios: FetchedResults<Scenario>

...

.onAppear() {

   print("onAppear caseid: \(myObject.Uid)")
   scenarios.nsPredicate = NSPredicate(format: "caseid == %@", myObject.Uid as CVarArg)
            
}

Upvotes: 1

Views: 67

Answers (1)

malhal
malhal

Reputation: 30549

You could compute a FetchRequest with the predicate and pass it into a result view, e.g.

FetchedResultsView(request: FetchRequest<Scenario>(sortDescriptors: [SortDescriptor(\.name)], predicate: NSPredicate(format: "caseid == %@", myObject.Uid as CVarArg))
} results in
struct FetchedResultsView<Content, Result>: View where Content: View, Result: NSFetchRequestResult {
    @FetchRequest var results: FetchedResults<Result>
    let content: ((FetchedResults<Result>) -> Content)
    
    init(request: FetchRequest<Result>, @ViewBuilder content: @escaping (FetchedResults<Result>) -> Content) {
        self._results = request
        self.content = content
    }
    
    var body: some View {
        content(results)
    }
}

Upvotes: 0

Related Questions