【发布时间】:2017-11-21 20:00:11
【问题描述】:
我正在尝试将 SearchBar 添加到 TableView,它使用 CoreData 存储其数据。但是当我尝试搜索 TableView 时没有更新。我认为 fetch 正在工作,但表没有被更新。
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
return
}
else {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let sRequest: NSFetchRequest<Note> = Note.fetchRequest()
sRequest.predicate = NSPredicate(format: "SELF.title CONTAINS[cd] %@", searchText)
sRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
let fetchedResultsController = NSFetchedResultsController(fetchRequest: sRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
print(sRequest)
do {
try fetchedResultsController.performFetch()
} catch {
fatalError("Failed to fetch entities: \(error)")
}
self.mainTable.reloadData()
}
return
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = mainTable.dequeueReusableCell(withIdentifier: "prototypeCell")!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let tableRequest: NSFetchRequest<Note> = Note.fetchRequest()
tableRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
var fetchedResultsController = NSFetchedResultsController(fetchRequest: tableRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
do {
try fetchedResultsController.performFetch()
} catch {
fatalError("Failed to fetch entities: \(error)")
}
let noteCell = fetchedResultsController.object(at: indexPath)
cell.textLabel?.text = noteCell.title!
let formatter = DateFormatter()
formatter.dateFormat = "d.M.y, HH:mm"
let dateString = formatter.string(from: noteCell.date! as Date)
cell.detailTextLabel?.text = dateString
return cell
}
【问题讨论】:
-
您能否提供您的
cellForRowAtIndexPath代码? -
更新:添加了 cellForRowAt
标签: ios swift uitableview core-data uisearchbar