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

标签 swift uitableview core-data nspredicate

我是 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/

相关文章:

iphone - UISegmentedControl 不更新 View

Swift:带有 UITableViewCellStyle.Subtitle 的 UITableViewCell 中的多个detailTextLabel行

iphone - 核心数据并发(NSOperation)

ios - 无法在控制台中打印我的json数据?

ios - 将核心数据与 iCloud 同步

ios - 如果没有 LaunchScreen.storyboard,启动画面还能从哪里来?

ios - UIPageViewController 的第一页显示黑屏且未加载内容

ios - 使用设备旋转调整 tableView 的大小

swift - macOS 催化剂上钥匙串(keychain)项目的 PersistentRef

swift - 使用自定义函数删除表格 View 单元格