I have application with UITableViewController
, two UIViewController
and Core Data. I want to make UISearchController
for the first time. I looked on the other questions by this theme, but I have working incorrect UISearchController
. When I write into searchBar
, it give incorrect results. And I don't know how show them in the table view cell. Please help me.
My code in the UITableViewController
var resultSearchController: UISearchController!
var searchPredicate: NSPredicate?
var filteredObjects: [Note]? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = self.editButtonItem()
fetchedResultsController = NSFetchedResultsController(fetchRequest: allEmployeesFetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: "mynote", cacheName: "mynote") // both mynote
fetchedResultsController?.delegate = self
fetchedResultsController?.performFetch(nil)
// UISearchController setup
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.delegate = self
controller.searchResultsUpdater = self
controller.hidesNavigationBarDuringPresentation = false
controller.dimsBackgroundDuringPresentation = true
controller.searchBar.sizeToFit()
controller.searchBar.delegate = self
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
self.tableView.reloadData()
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchText = self.resultSearchController.searchBar.text
println(searchText)
if let searchText = searchText {
searchPredicate = NSPredicate(format: "mynote contains[c] %@", searchText)
filteredObjects = self.fetchedResultsController?.fetchedObjects?.filter() {
return self.searchPredicate!.evaluateWithObject($0)
} as! [Note]?
self.tableView.reloadData()
println(searchPredicate)
}
}
and
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if searchPredicate == nil {
return fetchedResultsController?.sections?.count ?? 0
} else {
return 1
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchPredicate == nil {
return fetchedResultsController?.sections?[section].numberOfObjects ?? 0 //0 default
} else {
return filteredObjects?.count ?? 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellNote", forIndexPath: indexPath) as! UITableViewCell
if searchPredicate == nil {
if var cellContact = fetchedResultsController?.objectAtIndexPath(indexPath) as? Note {
cell.textLabel?.text = cellContact.mynote
cell.detailTextLabel?.text = cellContact.mytime
return cell
}
}
return cell
}
My core data class has
import Foundation
import CoreData
@objc(Note)
class Note: NSManagedObject {
@NSManaged var mynote: String
@NSManaged var mytime: String
}
I found a solve, I changed my
UITableViewController