gpt4 book ai didi

swift - 使用 NSPredicate 对 TableView 中的核心数据进行排序(Swift)

转载 作者:可可西里 更新时间:2023-11-01 02:00:39 25 4
gpt4 key购买 nike

我是 Swift 中 Core Data 的新手,需要帮助使用 NSPredicate。我目前在我的应用程序中有一个表格 View 和一个搜索栏。我还有一个名为 Item 的实体,其属性为过敏原(字符串)。我想过滤此 TableView ,以便仅当 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

最佳答案

添加以下谓词以仅过滤与您的搜索文本完全匹配的那些:

fetchRequest.predicate = NSPredicate(format:"allergen == %@", searchBar.text)

或者,如果 allergen 字符串包含搜索文本,您可能想要匹配:

fetchRequest.predicate = NSPredicate(format:"allergen CONTAINS %@", searchBar.text)

要使比较大小写和变音符号不敏感,请添加 [cd](因此 ... ==[cd] ......包含[cd] ...).

关于swift - 使用 NSPredicate 对 TableView 中的核心数据进行排序(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46627346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com