DEV Community

Avelyn Hyunjeong Choi
Avelyn Hyunjeong Choi

Posted on

Core Data with Table Views Part II

In this blog, I will try to extend the app we built in Part I by adding a search bar in the Main View Controller so that you type in the search bar and it will filter the employees based on the name, age or phone. I will also add other entities and add relationships between these entities.

In MainVC, add setupSearchBar() to add the searchBar in UI.

import UIKit

class MainVC: UIViewController {
    ...
    private let searchBar = UISearchBar()
    override func viewDidLoad() {
        ...
        setupSearchBar()
    }...
}
Enter fullscreen mode Exit fullscreen mode

In extension MainVC, searchBar related functions are implemented as below.

extension MainVC: UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
    private func setupSearchBar() {
        searchBar.placeholder = "Search Employees"
        navigationItem.titleView = searchBar
        searchBar.delegate = self
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText.isEmpty {
            empArray = CoreDataHandler.shared.fetchData()
        } else {
            empArray = CoreDataHandler.shared.searchData(with: searchText)
        }
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchBar.text = ""
        searchBar.resignFirstResponder()
        empArray = CoreDataHandler.shared.fetchData()
    }
...
Enter fullscreen mode Exit fullscreen mode

Lastly, add searchData() in CoreDataHandler to retrieve data matching the user's input

class CoreDataHandler {
    ...
    func searchData(with searchText: String) -> [Emp] {
        let fetchRequest: NSFetchRequest<Emp> = Emp.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "name CONTAINS[c] %@ OR age == %@ OR phone CONTAINS[c] %@", searchText, searchText, searchText)
        do {
            let result = try context!.fetch(fetchRequest)
            return result
        } catch {
            print("Failed to search employees")
            return []
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Result

Image description
Image description
Image description

Add other entities and add relationships between these entities.

relationship

Image description

Image description

Image description

Full code is available in employeeCatalogue

Top comments (0)