icekomo
icekomo

Reputation: 9466

TableView doesn't update(reloadData) after CoreData change using FRC Swift 3

I have updated this question as I found another key to this problem. It seems that when I add something to CoreData, the tableview does not reload the data, even though I can print out the objects that CoreData has saved. So I know the data is correct, but the function func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell never gets called.

It's also worth noting that if I stop the application and reopen it , the table view displays the correct amount of cells and information. So it seems the the data only loads property on initial build.

I have a UITableView that is being populated by CoreData and also using a FetchedResultsController. I added the FRC delegate methods and I tried to force the tableView.reloadData() method, but that doesn't seem to work. The data shows up, if I stop the build and rebuild the project.

Here are my delegate methods that I am using:

    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.beginUpdates()
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {

    switch type {
    case .insert:
        tableView.insertRows(at: [newIndexPath!], with: .automatic)
    case .delete:
        tableView.deleteRows(at: [indexPath!], with: .automatic)
    case .update: 
       tableview.reloadData()
    case .move:
        tableView.deleteRows(at: [indexPath!], with: .automatic)
        tableView.insertRows(at: [newIndexPath!], with: .automatic)
    }
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
    tableView.endUpdates()
}

When I come back to this View I would like to force the tableview to reload its data.

ViewwillAppear method:

override func viewWillAppear(_ animated: Bool) {
    // load the data

    let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()
    fetchRequest.predicate = NSPredicate(format:"[email protected] >= 0")
    let sort = NSSortDescriptor(key: #keyPath(Person.name), ascending: true)
    fetchRequest.sortDescriptors = [sort]
    positiveFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: coreDataStack.managedContext, sectionNameKeyPath: nil, cacheName: nil)

    do{
     try positiveFetchedResultsController.performFetch()
     }catch let error as NSError{
        print("Fetching error: \(error), \(error.userInfo)")
    }


    let negativFetchRequest: NSFetchRequest<Person> = Person.fetchRequest()
    negativFetchRequest.predicate = NSPredicate(format:"[email protected] < 0")
    let negativeSort = NSSortDescriptor(key: #keyPath(Person.name), ascending: true)
    negativFetchRequest.sortDescriptors = [negativeSort]
    negativeFetchedResultsController = NSFetchedResultsController(fetchRequest: negativFetchRequest, managedObjectContext: coreDataStack.managedContext, sectionNameKeyPath: nil, cacheName: nil)

    do{
        try negativeFetchedResultsController.performFetch()
    }catch let error as NSError{
        print("Fetching error: \(error), \(error.userInfo)")
    }

    positiveFetchedResultsController.delegate = self
    negativeFetchedResultsController.delegate = self

    print("\(positiveFetchedResultsController.fetchedObjects!.count) positive fetch count")
    //print("\(positiveFetchedResultsController.fetchedObjects![0].statement!.count) positive statements count")
    print("\(negativeFetchedResultsController.fetchedObjects!.count) negative fetch count")
    //print("\(negativeFetchedResultsController.fetchedObjects![0].statement!.count) negative statements count")

    tableView.reloadData()
}

Here is my cellForRowAt method:

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "personCell", for: indexPath) as! PersonTableViewCell

    switch(indexPath.section) {
    case 0:
        //print("this is section 0")
        let person = positiveFetchedResultsController.object(at: indexPath)
        cell.personName.text = person.name
        //print("\(person.name!) is the name")
        //print("\(person.statement!.count) postive person statement count")

        if(person.statement!.count == 0){
            print("default")
            cell.statementAmount.text = "$0.00"
        }
        else{
            //print("\(person.name!) has \(person.statement!.count) statement count")
            let amountTotal = person.value(forKeyPath: "[email protected]") as? Decimal
            //print("\(amountTotal!) this is the total")
            cell.statementAmount.text = convertStringToDollarString(amountToConvert: String(describing: amountTotal!))

        }

    case 1:

        print("this is section 1")
        //print("\(negativeFetchedResultsController.object(at: [indexPath.row,0])) objects fetched")
        //print("\(indexPath.section) section number")
        //print("\(indexPath.row) row number")

        let person = negativeFetchedResultsController.fetchedObjects![indexPath.row]
        cell.personName.text = person.name

        print("\(person.name!) is the name")
        print("\(person.statement!.count) negative person statement count")

        if(person.statement!.count == 0){
            cell.statementAmount.text = "$0.00"
        }
        else{
            //print("\(person.name!) has \(person.statement!.count) statement count")
            let amountTotal = person.value(forKeyPath: "[email protected]") as? Decimal
            print("\(amountTotal!) this is the total")
            cell.statementAmount.text = String(describing: amountTotal!)

            cell.statementAmount.text = convertStringToDollarString(amountToConvert: String(describing: amountTotal!))
        }

        cell.backgroundColor = Styles.redColor();

        let bgColorView = UIView()
        bgColorView.backgroundColor = Styles.darkRedColor()
        cell.selectedBackgroundView = bgColorView

    default: cell.personName.text = "hello"
    }
    return cell
}

Upvotes: 0

Views: 1405

Answers (2)

user6202541
user6202541

Reputation: 1

  • To do this you can simply add fetchedResultsController.delegate = nil in viewWillAppear function before calling table reloadData.

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchedResultsController.delegate = nil
self.tableView.reloadData()
}

Upvotes: 0

heyjude
heyjude

Reputation: 31

maybe try this:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.tableView.reloadData()
}

Upvotes: 1

Related Questions