我是Swift中Core Data的新手,需要使用NSPredicate帮助。我目前在我的应用程序中有一个表格视图和一个搜索栏。我还有一个名为Item的实体,其属性为过敏原(string)。我想过滤此表视图,以便只有在searchBar.text等于Item.allergen时才显示单元格。
func attemptFetch() {
let fetchRequest: NSFetchRequest<Item> = Item.fetchRequest()
let dateSort = NSSortDescriptor(key: "created", ascending: false)
let titleSort = NSSortDescriptor(key: "title", ascending: true)
if segment.selectedSegmentIndex == 0 {
fetchRequest.sortDescriptors = [dateSort]
} else if segment.selectedSegmentIndex == 1 {
fetchRequest.sortDescriptors = [titleSort]
} else {
if searchBar.text != nil, searchBar.text != ""{
print("Search bar text exists")
print(searchBar.text!)
fetchRequest.sortDescriptors = [titleSort]
//Search; Only display cell if searchBar.text = Item.allergen
} else {
print("Search bar text does not exist!")
fetchRequest.sortDescriptors = [titleSort]
}
}
let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
controller.delegate = self
self.controller = controller
do {
try controller.performFetch()
} catch {
let error = error as NSError
print("\(error)")
}
}
我尝试使用NSPredicate执行此操作,但它导致实体错误中找不到关键路径。我会包含这段代码,但我确定这是完全错误的。
有什么建议吗?
更新
Here's a picture of the Item entity's attributes in the Core Data Model. This is the code in the ItemEntity.swift file, I think this was autogenerated?希望这就是您所需要的。
更新2: 谢谢您的帮助!我找到了解决方案。这是对我有用的代码:
let userSearch = searchBar.text!
commitPredicate = NSPredicate(format: "allergen == %@", userSearch)
fetchRequest.predicate = commitPredicate
答案 0 :(得分:0)
添加以下谓词,仅过滤与搜索文本完全匹配的谓词:
fetchRequest.predicate = NSPredicate(format:"allergen == %@", searchBar.text)
或者,如果allergen
字符串包含搜索文本,您可能希望匹配:
fetchRequest.predicate = NSPredicate(format:"allergen CONTAINS %@", searchBar.text)
要使比较大小写和变音符号不敏感,请添加[cd]
(所以... ==[cd] ...
或... CONTAINS[cd] ...
)。