使用 NSPredicate 对 Table 视图中的核心数据进行排序 (Swift)

Using NSPredicate to Sort Core Data in a Table View (Swift)

我是 Swift 中 Core Data 的新手,需要帮助使用 NSPredicate。我目前在我的应用程序中有一个 table 视图和一个搜索栏。我还有一个名为 Item 的实体,其属性为过敏原(字符串)。我想过滤此 table 视图,以便单元格仅在 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?希望这就是您所需要的。

更新二: 谢谢您的帮助!我找到了解决办法。这是对我有用的代码:

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] ...... CONTAINS[cd] ...)。