【发布时间】:2020-04-08 04:50:34
【问题描述】:
我正在尝试为现有的 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() 语句中对获取的结果调用谓词相关方法,但它们似乎都不起作用。
如果有任何问题,请不要犹豫。
【问题讨论】:
标签: search core-data swiftui predicate