'What is the correct way to reload a tableView from inside a nib?

I have a tableview which shows a custom cell. Inside the cell is a button.

Once the button is clicked, a network call is made and the tableview should reload.

I tried this, but I get Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value at vc.reloadData().

  @IBAction func acceptRequestPressed(_ sender: UIButton) {
       
        DatabaseManager.shared.AnswerFriendRequest(emailFriend: friendNameLabel.text!, answer: true) { success in
            if success {
                
                let vc = FriendRequestViewController()
                vc.reloadData()
                
            }else {
                print ("error at answer")
            }
        }
    }


Solution 1:[1]

Few pointers:

  1. You can have a closure upon the data call completion in your class that has the table view. Eg:

    // Custom Table Cell Class class CustomCellClass: UITableViewCell {

     let button = UIButton()
     // All other UI set up
    
     // Create a closure that your tableView class can use to set the logic for reloading the tableView
     public let buttonCompletion: () -> ()
    
     @IBAction func acceptRequestPressed(_ sender: UIButton) {
    
         DatabaseManager.shared.AnswerFriendRequest(emailFriend: friendNameLabel.text!, answer: true) { [weak self] success in
             if success {
                 // Whatever logic is provided in cellForRow will be executed here. That is, tableView.reloadData() 
                 self?.buttonCompletion() 
    
             }else {
                 print ("error at answer")
             }
         }
     }
    

    }

// Class that has tableView:

class SomeViewController: UIViewController {

    private let tableView = UITableView()
    .
    .
    // All other set up, delegate, data source
    
    func cellForRow(..) {
       let cell = tableView.dequeueTableViewCell(for: "Cell") as! CustomCellClass
    
        cell.buttonCompletion = {[weak self] in
            tableView.reloadData()
       }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 my3vshenoy