I've got a tableview populated by Core Data with multiple dynamic sections and I want to use a UISearchController to search for specific records. Every tutorial I've found says to use an array of fetched results, combined with a filtered array to display the results, but this is a pain for maintaining my tableview sections.
The code I have totally works, in that I just perform a fetch every time the user types in the search field, but I realize this is more expensive as far as resources go.
So how would I implement a filter on arrays while MAINTAINING my tableview sections? Arrays of arrays?
My current code:
//MARK: Search Deletegate Methods
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchText = self.searchController.searchBar.text
let selectedScopeButtonIndex = self.searchController.searchBar.selectedScopeButtonIndex
self.filterContentForSearch(searchText, scope: selectedScopeButtonIndex)
self.tableView.reloadData()
}
func filterContentForSearch(searchText: String, scope: Int)
{
println("Fired")
//Way too expensive for resources
var fetchRequest = NSFetchRequest()
fetchRequest = NSFetchRequest(entityName: "FoodItem")
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
let mealDescriptor = NSSortDescriptor(key: "meal", ascending: true)
fetchRequest.sortDescriptors = [mealDescriptor,sortDescriptor]
//Predicate
if searchText != ""
{
let namePredicate = NSPredicate(format: "name CONTAINS[cd] %@", searchText)
fetchRequest.predicate = namePredicate
}
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: "meal", cacheName: nil)
fetchedResultsController.delegate = self
fetchedResultsController.performFetch(nil)
}