简体   繁体   English

不在Coredata的Tableview中显示搜索结果?

[英]Not Showing Search results in Tableview From Coredata?

Hello I'am Creating an app for storing College data and Student data, Crud Operation is working perfectly with Relation in Coredata, I am facing issue while searching data from tableview with search bar.您好,我正在创建一个用于存储大学数据和学生数据的应用程序,Crud 操作与 Coredata 中的关系完美配合,我在使用搜索栏从 tableview 搜索数据时遇到问题。 I'm Programmatically Creating UISearch bar.我正在以编程方式创建 UISearch 栏。 I have some did some research too, but nothing works for me.我也有一些人做了一些研究,但对我没有任何帮助。 Can Any one please tell me why is this happening.谁能告诉我为什么会这样。 I did Debugging Too... and on This Line I find the issue.我也进行了调试......在这条线上我发现了问题。

for name in collegeList{
        if((name.collegeName?.lowercased().contains(searchText.lowercased())) != 
   nil) 
       {
        filteredData.append(name)
        }
    }

Here's My details:-这是我的详细信息:-

import UIKit
import TransitionButton
import CoreData
class CollegeListViewController: 
CustomTransitionViewController,UISearchResultsUpdating, 
UISearchBarDelegate,UISearchControllerDelegate{
@IBOutlet weak var collegeTableView: UITableView!
var collegeList = [College]()
var filteredData = [College]()
var searching = false
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
    super.viewDidLoad()
    collegeTableView.delegate = self
    collegeTableView.dataSource = self
    //collegeList = DataBaseHelper.shared.fetchCollegeList()
}


override func viewWillAppear(_ animated: Bool) {
    ConfigurationSearchController()
    collegeList = DataBaseHelper.shared.fetchCollegeList()
    DispatchQueue.main.async {
        self.collegeTableView.reloadData()
    }
}

@IBAction func collegeAddDataButtonTapped(_ sender: UIBarButtonItem) {
    let formVC : CollegeFormViewController = 
self.storyboard?.instantiateViewController(withIdentifier: "CollegeFormViewController") as! CollegeFormViewController
    self.navigationController?.pushViewController(formVC, animated: true)
}

func ConfigurationSearchController(){
    searchController.searchBar.delegate = self
    searchController.searchResultsUpdater = self
    searchController.loadViewIfNeeded()
    searchController.obscuresBackgroundDuringPresentation = false
    searchController.searchBar.enablesReturnKeyAutomatically = false
    searchController.searchBar.returnKeyType = UIReturnKeyType.done
    self.navigationItem.searchController = searchController
    self.navigationItem.hidesSearchBarWhenScrolling = false
    definesPresentationContext = true
    searchController.searchBar.placeholder = "Search"
    
    
    
    
}

func updateSearchResults(for searchController: UISearchController) {
    let searchText = searchController.searchBar.text!
    if !searchText.isEmpty{
        searching = true
        filteredData.removeAll()
        //guard let college = collegeList else { return }
        for name in collegeList{
            if ((name.collegeName?.lowercased().contains(searchText.lowercased())) != 
       nil) 
           {
            filteredData.append(name)
            }
        }
    } else {
        searching = true
        filteredData.removeAll()
        filteredData = collegeList
    }
    collegeTableView.reloadData()
}

}


  extension CollegeListViewController : UITableViewDelegate, UITableViewDataSource {

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
 {
    if searching{
        return filteredData.count
    } else {
        return collegeList.count
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> 
 UITableViewCell {
    let cell = collegeTableView.dequeueReusableCell(withIdentifier: "collegeCell") 
as! CollegeListTableViewCell
    let row = collegeList[indexPath.row]
    if searching {
        let filter = filteredData[indexPath.row]
        cell.lblAddress.text = filter.collegeAddress
        cell.lblCollegeName.text = filter.collegeName
        cell.lblCity.text = filter.collegeCity
        cell.lblUniversity.text = filter.collegeUniversity
    } else {
        cell.lblAddress.text = row.collegeAddress
        cell.lblCollegeName.text = row.collegeName
        cell.lblCity.text = row.collegeCity
        cell.lblUniversity.text = row.collegeUniversity
    }
    return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

This Is My Coredata functions Details:-这是我的 Coredata 函数详细信息:-

import Foundation
import CoreData
import UIKit

class DataBaseHelper: NSObject {

static let shared = DataBaseHelper()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

func saveData(object : [String : String]) {
    let college = NSEntityDescription.insertNewObject(forEntityName: "College", into: context) as! College
    college.collegeName = object["collegeName"]
    college.collegeAddress = object["collegeAddress"]
    college.collegeCity = object["collegeCity"]
    college.collegeUniversity = object["collegeUniversity"]
    
    do {
        try context.save()
    } catch let error {
        print(error.localizedDescription)
    }
    
}
func fetchCollegeList()-> [College] {
    var college = [College]()
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "College")
    do {
        college =  try context.fetch(fetchRequest) as! [College]
    } catch let error {
        print(error.localizedDescription)
    }
    return college
}

func deleteData(index:Int) -> [College] {
    var college = fetchCollegeList()
    context.delete(college[index])
    college.remove(at: index)
    do {
        try context.save()
    } catch  {
        print(error.localizedDescription)
    }
    return college
}

func editData(object:[String: String], index: Int) {
    let college = fetchCollegeList()
    college[index].collegeName = object["collegeName"]
    college[index].collegeUniversity = object["collegeUniversity"]
    college[index].collegeAddress = object["collegeAddress"]
    college[index].collegeAddress = object["collegeAddress"]
    do {
        try context.save()
    } catch  {
        print(error.localizedDescription)
    }
}}
class CollegeListViewController:
CustomTransitionViewController,UISearchResultsUpdating,
UISearchBarDelegate,UISearchControllerDelegate{
@IBOutlet weak var collegeTableView: UITableView!
var collegeList = [College]()
var filteredData = [College]()
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
    super.viewDidLoad()
    collegeTableView.delegate = self
    collegeTableView.dataSource = self
    collegeList = DataBaseHelper.shared.fetchCollegeList()
    filteredData = collegeList
}

override func viewWillAppear(_ animated: Bool) {
    ConfigurationSearchController()
    collegeTableView.reloadData()
}

@IBAction func collegeAddDataButtonTapped(_ sender: UIBarButtonItem) {
    let formVC : CollegeFormViewController =
    self.storyboard?.instantiateViewController(withIdentifier: "CollegeFormViewController") as! CollegeFormViewController
    self.navigationController?.pushViewController(formVC, animated: true)
}

func ConfigurationSearchController(){
    searchController.searchBar.delegate = self
    searchController.searchResultsUpdater = self
    searchController.loadViewIfNeeded()
    searchController.obscuresBackgroundDuringPresentation = false
    searchController.searchBar.enablesReturnKeyAutomatically = false
    searchController.searchBar.returnKeyType = UIReturnKeyType.done
    self.navigationItem.searchController = searchController
    self.navigationItem.hidesSearchBarWhenScrolling = false
    definesPresentationContext = true
    searchController.searchBar.placeholder = "Search"
}

func updateSearchResults(for searchController: UISearchController) {
    let searchText = searchController.searchBar.text!
    guard !searchText.isEmpty else {
        filteredData = collegeList
        return
    }
    filteredData = collegeList.filter({ $0.collegeName.lowercased().contains(searchText.lowercased() )})
    collegeTableView.reloadData()
}

} }

extension CollegeListViewController: UITableViewDelegate, UITableViewDataSource {扩展 CollegeListViewController: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell {
    let cell = collegeTableView.dequeueReusableCell(withIdentifier: "collegeCell")
    as! CollegeListTableViewCell
    let filter = filteredData[indexPath.row]
    cell.lblAddress.text = filter.collegeAddress
    cell.lblCollegeName.text = filter.collegeName
    cell.lblCity.text = filter.collegeCity
    cell.lblUniversity.text = filter.collegeUniversity
    return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableView.automaticDimension
}

} }

I think this should do it now.我认为现在应该这样做。 Basically you don't need the searching variable.基本上你不需要searching变量。 You just use the filterd list on the collection for everything and keep the collegeList just to filter the results and refresh the filtered list.您只需将集合上的过滤列表用于所有内容,并保留collegeList 仅用于过滤结果并刷新过滤列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM