I am trying to build a search view for an existing CoreData app (simple logging app).
I have all the data stored with CoreData and is fetched with the @FetchRequest:
@State private var searchPredicate: NSPredicate? = NSPredicate(format: "title contains[c] %@", "")
@FetchRequest( entity: Item.entity(), sortDescriptors: [NSSortDescriptor(keyPath: Item.title, ascending: true)],
predicate: NSPredicate(format: "title contains[c] %@", "h")
)
var items: FetchedResults<Item>
It now only fetches the items that pass the predicate test which in this case are all the ones that contain an "h".
I then display the results in a List in the body of the SearchView:
List {
ForEach(Items) { Item in
ListViewItem(title: Item.title!, subTitle: Item.subTitle!, createdAt: "(Item.createdAt!)")
}
}
I then created a new class "Searchbar" which is called in the searchview and is supposed to create a predicate based on the input of the search field and then pass it on as a Binding to the parent where then based on that predicate the correct items can be displayed.
Calling the searchbar at the top of a VStack in the searchview:
SearchBar(text: $searchText, predicate: $searchPredicate)
The Bindings change depending on the user input in the "searchBar":
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
text = searchText
predicate = NSPredicate(format: "title contains[c] %@", searchText)
}
So far so good...
The problem I have now run into is that we have a predicate that works but can't be called within the @Fetchrequest in the definitions since it would be called before its initialized.
@State private var searchPredicate: NSPredicate? = NSPredicate(format: "title contains[c] %@", "")
@FetchRequest(
entity: Item.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: Item.title, ascending: true)
],
predicate: searchPredicate
) var items: FetchedResults<Item>
This gives me the error that the property initializer can't be run before self is available which is logical but makes me wonder and brings me back to my question: Is there a way to modify fetched results with a predicate after they are initialized?
I have also tried calling predicate related methods on the fetched results in the ForEach() statement but none of them seemed to have worked.
If there are any questions please do not hesitate to ask.
See Question&Answers more detail:
os