Updating fetchedResultsController for predicate set by UISearchBar

淺唱寂寞╮ 提交于 2019-12-04 17:27:01

This is not-so-swift-pseudo-code... it most assuredly will not compile with any swift compiler.

Your FRC is not using a cache, so there is no cache to be deleted, and we can just assign the predicate to the existing FRC fetch request.

You may not want to do a complete new fetch on every character change in the search bar, or you may want to only do the search on the first character, and use subsets for subsequent characters.

// called when text changes (including clear)
internal func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    var predicate:NSPredicate = nil
    if searchBar.text.length != 0 {
        predicate = NSPredicate(format: "(songDescription contains [cd] %@) || (songStar contains[cd] %@)", searchBar.text!, searchBar.text!)
    }
    fetchedResultsController.fetchRequest.predicate = predicate
    fetchedResultsController.performFetch()
    tableView.reloadData()
}

// called when cancel button pressed
internal func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
    searchBar.text = ""
    fetchedResultsController.fetchRequest.predicate = nil
    fetchedResultsController.performFetch()
    tableView.reloadData()
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!