简体   繁体   中英

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. I'm Programmatically Creating UISearch bar. 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:-

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 {

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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