2
votes

In swift I have two view controllers. One is a tableView and displays data from an array. On a function call the other view controller calls the tableView and delivers arguments with new data for the table view. Even when I update the array buckets where the data is taken from the TableView doesn't update. How do I get the program to reload its data?

TABLE VIEW

import Foundation
import UIKit
class BucketTableViewController: UITableViewController {
    var buckets = ["A", "B", "C"]
    override func viewDidLoad() {
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return buckets.count
    } 
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
        cell.textLabel?.text = buckets[indexPath.row]
        return cell
    }
    func updateBuckets(newBucket: NSArray) {
        buckets = newBucket as! [String]
        self.tableView?.reloadData()
    } 
}

I can verify that updateBuckets is called from the other view controller.

OTHER VIEW CONTROLLER

    var bigArray = ["M", "A", "R", "C"]

override func viewDidLoad() {
    super.viewDidLoad()
    let buckets = BucketTableViewController()
    buckets.updateBuckets(bigArray)

}
3
Have you checked, that the tableView already exists at the time you call updateBuckets? - freytag
@freytag I just threw the updateBuckets in a delayed method and that didn't change the outcome. So yes, the tableView is already created - Marcus
Did you checked that tableView's delegate and dataSource is not nil's? - anatoliy_v

3 Answers

5
votes

Try using tableView?.beginUpdates() and tableView?.endUpdates() instead - I've found that tableView?.reloadData() can be finicky about data source updates sometimes.

Otherwise, make sure you're calling updateBuckets() on the right instance of BucketTableViewController(); it looks like you instantiated a new instance in your viewDidLoad() instead of changing the content of an existing instance (as you presumably would be doing).

0
votes

This line right here:

let buckets = BucketTableViewController()

You're creating a brand new BucketTableViewController instance and updating its buckets. That's not going to cause the existing BucketTableViewController to update. You need to figure out how to get a reference to the existing view controller and update it instead.

-1
votes