How to reload tableview using view controller (swift)

Your problem is that tb is a local variable, so it is not visible outside of viewDidLoad().

If you make tb a property (a.k.a. instance variable) of your view controller, then you can use it from any of the controller’s methods:

class ViewController3: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var Person_data = [Person]()

    private var tb: UITableView?  // Now the scope of tb is all of ViewController3...

    override func viewDidLoad() {
        super.viewDidLoad()

        // ...so it is visible here...

        tb = UITableView(frame: CGRect(x: 10, y: 50, width: 200, height:600), style: UITableViewStyle.Plain)

        ...
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        fetch_data()      

        tb?.reloadData()   // ...and it is also visible here.
    } 

Note that in your code, the fact that tb is a local variable doesn’t mean that your UITableView object disappears when viewDidLoad() finishes. It means that your reference to the UITableView disappears. The table view object itself lives on because it is added to your view hierarchy, but you don’t have a reference to it anymore because your variable went out of scope.

For further reading on the distinction between variables and the objects they reference, search for “scope” and “pass by reference.”


You can access your tableView IBOutlet in viewWillAppear:, you can also call reloadData. I'm not sure why you think you can't, but it should work fine.