I am working on a SwiftUI project and in a subview I use @FetchRequest to fetch data from CoreData. I have a menu to let user select which data to fetch, and by default I want to fetch all datas.
The problem is when user open the menu and select a category then it refetch the data, it's correct and when user close the menu, the nsPredicate that the user have given will disappear and switch to the default predicate.
I tried to write the same pattern code on 'EarthQuake' sample app, it has the same problem.
And here is the code:
List(selection: $selection) {
ListView(search: $searchText)
}
.background(toggle ? Color.red.opacity(0.01) : nil)
.toolbar {
ToolbarItem(placement: .bottomBar) {
Button {
toggle.toggle()
} label: {
Text("Toggle")
}
}
}
.searchable(text: $searchText)
ListView:
struct ListView: View {
@FetchRequest(sortDescriptors: [SortDescriptor(\.time, order: .reverse)]) // predicate: nil
private var quakes: FetchedResults<Quake>
@Binding var search: String
var body: some View {
ForEach(quakes, id: \.code) { quake in
NavigationLink(destination: QuakeDetail(quake: quake)) {
QuakeRow(quake: quake)
}
}
.onChange(of: search) { newValue in
quakes.nsPredicate = newValue.isEmpty ? nil : NSPredicate(format: "place CONTAINS %@", newValue)
}
}
}
I can filter data by typing in the search field but when I click on Toggle Button, it may refresh the ParentView which cause the @fetchRequest to update and nsPredicate return to nil.
Is this a bug? Or maybe my understand was wrong. And is there any good suggestions?