Rakshith G B
Rakshith G B

Reputation: 826

How to update Data in tableview using swift?

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.

Upvotes: 10

Views: 11211

Answers (2)

Suragch
Suragch

Reputation: 512536

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

self.tableView.reloadData()

Upvotes: 2

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71852

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.

Upvotes: 8

Related Questions