我正在尝试为现有 CoreData 应用程序(简单的日志记录应用程序)构建搜索视图。
我将所有数据存储在 CoreData 中,并使用@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>
现在,它只获取通过谓词测试的项目,在本例中是所有包含“h”的项目。
然后,我将结果显示在 SearchView 正文的列表中:
List {
ForEach(Items) { Item in
ListViewItem(title: Item.title!, subTitle: Item.subTitle!, createdAt: "\(Item.createdAt!)")
}
}
然后,我创建了一个新类“Searchbar”,它在搜索视图中调用,应该根据搜索字段的输入创建一个谓词,然后将其作为绑定传递给父级,然后根据该谓词创建正确的项目可以显示。
在搜索视图中调用 VStack 顶部的搜索栏:
SearchBar(text: $searchText, predicate: $searchPredicate)
绑定根据“searchBar”中的用户输入而变化:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
text = searchText
predicate = NSPredicate(format: "title contains[c] %@", searchText)
}
到目前为止,一切都很好...
我现在遇到的问题是,我们有一个谓词可以工作,但无法在定义中的 @Fetchrequest 中调用,因为它会在初始化之前被调用。
@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>
这给了我一个错误,即属性初始值设定项无法在 self 可用之前运行,这是合乎逻辑的,但让我想知道并让我回到我的问题:有没有办法在初始化后使用谓词修改获取的结果?
我还尝试对 ForEach() 语句中获取的结果调用谓词相关方法,但它们似乎都不起作用。
如果有任何疑问,请随时询问。