How to update Data in tableview using swift?

10,412

Solution 1

You can use NSNotificationCenter for update your tableView from another view.

Your -addObserver: declaration has to be like this in your tableView Controller in viewDidLoad method:

override func viewDidLoad() {
    super.viewDidLoad()
     NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshTable:", name: "refresh", object: nil)
}

And your function for this addObserver will like:

 func refreshTable(notification: NSNotification) {

    println("Received Notification")
    self.tableView.reloadData()
}

Now you can post notification like this when you navigate to your tableView controller:

NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: nil, userInfo: nil)

Check THIS sample project for more Info.

Hope it will help you.

Solution 2

Under normal circumstances, the way to update data in a UITableView is

self.tableView.reloadData()
Share:
10,412
Rakshith G B
Author by

Rakshith G B

Updated on July 20, 2022

Comments

  • Rakshith G B
    Rakshith G B almost 2 years

    Currently I have 3 swift files: ManualViewController, AutoViewController, Main

    ManualViewController is the UIViewController with a table view. AutoViewController is a UIViewController with a few buttons. Main is just a swift file with all the data for table view.

    ManualViewController and AutoViewController are controlled using TabBarController.

    When I run the app the initial contents found in Main.swift is loaded onto the table view. When I go to the next view i.e AutoViewController and click on a button to change data in Main.swift, the data changes. The problem is when I switch back to ManualViewController the table still contains the old data and not the updated one.

    I also tried this:

    override func viewWillAppear(animated: Bool) 
    {
        super.viewWillAppear(false)
        self.tableView.reloadData()
    }
    

    It still din't work.