快速获取fetchedresultscontroller的Searchbar实现

问题描述

coredata中存在的数据已成功显示在tableview上。但是,当我尝试使用fetchedresultscontroller实现搜索栏时,它无法正常工作。我正在添加我的代码。任何人都可以检查它并帮助我解决问题。 Mycode是-

func numberOfSections(in tableView: UITableView) -> Int {
    if let sections = fetchedResultsController?.sections {
        return sections.count
    }
    return 0
}

func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
    if let sections = fetchedResultsController?.sections {
        return sections[section].numberOfObjects
    }
    return 0
}

func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PatientListTableViewCell",for: indexPath) as? PatientListTableViewCell
    
    if let patientData = fetchedResultsController?.object(at: indexPath) {
        cell?.patientName.text = patientData.name
        cell?.patientIdLabel.text = patientData.id
        cell?.location_Lbl.text = patientData.streetAdress
    }
    
    return cell!
}

func searchBar(_ searchBar: UISearchBar,textDidChange searchText: String) {
    if searchBar.text?.count != 0 {
        let predicate = nspredicate(format: "name CONTAINS %@",searchBar.text!)
        
        fetchedResultsController!.fetchRequest.predicate = predicate
        
        do {
            try self.fetchedResultsController!.performFetch()
            searching = true
            tableView.reloadData()
        } catch let error as NSError {
        }
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searching = false
        searchBar.text = ""
        tableView.reloadData()
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.endEditing(true)
        searching = false
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)