mitchkman
mitchkman

Reputation: 6680

Notify table view to reload data

I have this table view controller:

class EventListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource {

    // Event table view
    @IBOutlet weak var eventTableView: UITableView!

    var events: [Event] = []
    ...

I would like to load the data asynchronously from a web service, this can take up to 5 seconds.

I have this asynchronous code:

override func viewDidLoad() {
    super.viewDidLoad()
    ...
    // ApiClient is a custom wrapper for my API
    ApiClient.sharedInstance.getEvents({
        (error: NSError?, events: [Event]) in

        // All this runs within an asynchronous thread

        if let error = error {
            println("Error fetching events")
            println(error.localizedDescription)
        }

        self.events = events
        // How to notify the table view?
    })
    ...

The data loads fine, but the table stays empty. Once viewWillAppear(...) is called again, the data is in the table.

Do I need to notify the table view? What's the cleanest way / best practice?

Thanks!

Upvotes: 2

Views: 1506

Answers (2)

AliSoftware
AliSoftware

Reputation: 32681

Simply call self.eventTableView.reloadData().

If your code in your closure is executed on an asynchronous thread, you may need to encapsulate that call into a dispatch_async call so that it is triggered on the main thread (because all UI-related work must always be run in the main thread):

// All this runs within an asynchronous thread
...
self.events = events

// Notify the tableView to reload its data.
// We ensure to execute that on the main queue/thread
dispatch_async(dispatch_get_main_queue()) {
  self.eventTableView.reloadData()
}

Upvotes: 5

Josh Gafni
Josh Gafni

Reputation: 2881

To refresh the tableView calling cellForRowAtIndexPath, you do:

self.eventTableView.reloadData()

Upvotes: 2

Related Questions