user979331
user979331

Reputation: 11871

Swift tableView.reloadData() not working inside completion handler

I have two view controllers, in controller 1 I have a table view and I am presenting the controller 2 like so:

@IBAction func addPOItemButtonPressed(_ sender: Any) {
        
        let itemViewController = self.storyboard?.instantiateViewController(withIdentifier: "LPOsItemController") as! LPOsItemController
        
        itemViewController.RequestID = self.RequestID
        
        let navigationViewController = UINavigationController(rootViewController: itemViewController)
        self.present(navigationViewController, animated: true, completion: nil)
        
    }

When I dismiss controller 2 I am calling a method in controller 1 like so:

In Controller 1:

NotificationCenter.default.addObserver(self, selector: #selector(self.refreshDetails(notification:)), name:NSNotification.Name(rawValue: "refreshDetails"), object: nil)


@objc func refreshDetails(notification: NSNotification){

        spLPOHeaderGet() { result in

                self.tableView.reloadData()

        }
        
    }

In Controller 2

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshDetails"), object: nil)
        
dismiss(animated: true, completion: nil)

My problem is when I call the method in Controller 1, the table view does not reload the data, sometimes it does and sometimes it doesn't. The reload call is in a completion handler. Can someone tell me what I am doing wrong?

Thanks,

Upvotes: 0

Views: 173

Answers (1)

Manish Punia
Manish Punia

Reputation: 877

Posting to notification for this situation is not a good idea. You can use the delegate to communicate from ViewController 2 to controller 1.

if you want to identify an issue in the current implementation try to put a breakpoint on

self.tableView.reloadData()

and check this method is called. and if it is called does tableview is in memory when this called. There is a chance when the completion handler is called this tableView object is deallocted.

Upvotes: 1

Related Questions