aleza aleza - 3 years ago 230
Swift Question

Populate table view after NSPredicate

I have a search bar with core data and I've an issue.

When I search something the NSPredicate show the results on playground but I cannot reload the table view and them doesn't show anything.

I would like to know if I can reload the table with this code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
var person = people[indexPath.row]
if searchController.searchBar.text != "" {
person = filteredPeople[indexPath.row]
cell.textLabel?.text = person.value(forKeyPath: "name") as? String
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
return cell

or I need to create a fetchResultsController.

filteredPeople is obtain after fetchRequest:

let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person")
let predicate = NSPredicate(format: "name contains[c] %@",searchController.searchBar.text!)
fetchRequest.predicate = predicate
do {
let filteredPeople = try! managedContext.fetch(fetchRequest) as! [Person]
for result in filteredPeople as [Person] {

All the best.

Answer Source

This is a common mistake.

You are declaring a local variable with the let keyword which is not the same object as the data source array.

Remove let

filteredPeople = try! managedContext.fetch(fetchRequest) as! [Person]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download