【问题标题】:Using NSPredicate to Sort Core Data in a Table View (Swift)使用 NSPredicate 对表视图中的核心数据进行排序 (Swift)
【发布时间】:2017-10-08 03:50:26
【问题描述】:

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

【问题讨论】:

  • 你也可以在这里发布你的项目类吗?想查看类的属性。
  • 不相关但为什么总是创建新的获取结果控制器?添加属性sortDescriptors并使用didSet观察者更新控制器谓词的sortDescriptors并执行获取。
  • 选择分段控制器时是否要对对象进行排序?
  • 排序对象部分工作正常。如果选择段 3(搜索段),并在搜索栏中输入文本(searchBar.text),我想过滤核心数据,以便只显示过敏原属性等于 searchBar.text 的单元格。

标签: swift uitableview core-data nspredicate


【解决方案1】:

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

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

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

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

要使比较大小写和变音符号不敏感,请添加[cd](即... ==[cd] ...... CONTAINS[cd] ...)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 2017-08-30
    • 2010-12-27
    相关资源
    最近更新 更多