Reputation: 1827
How do I reload a UiTableView only after the data has been loaded from the database. I have a datasource class that contains the function to load in all the data, and stores the data after it has been loaded into an array.
When I access the data using the Tableview though it displays nothing because the tableview loads before the database has returned its data. The only way to load the data is for me to have a button that manually reloads the tableview.
How do I cause the tableview to automatically reload once the array in the datasource object has been populated from the database?
Upvotes: 3
Views: 2125
Reputation: 1827
Being a new programmer it took me a while to learn this was even possible, but I just realized completion blocks are the way to go. It will carry out some specified code only after your function has finished fetching from the database. In this case, I can update the tableview AFTER I've retrieved the data from the database. Here's an example.
Function definition:
func getDataFromDatabase(someInput: Any, completion: @escaping(String?) -> Void) {
let retrievedData: String = databaseCallFunction()
// 'Get data from database' code goes here
// In this example, the data received will be of type 'String?'
// Once you've got your data from the database, which in this case is a string
// Call your completion block as follows
completion(retrievedData)
}
How to call the function:
getDataFromDatabase(someInput: "Example", completion: { (data) in
// Do something with the 'data' which in this example is a string from the database
// Then the tableview can be updated
let tableView.title = data
tableView.reloadTableView
})
The code in the completion block will happen AFTER the database call has completed.
Upvotes: 6
Reputation: 2882
Why not just call tableView.reloadData() once you've populated your data? It'll repopulate the entire table (well technically it'll only re-create whatever cells are visible).
The point is that your tableView:cellForRowAt: method should have the ability to access your data so as to fill in each table cell appropriately based on that data. Anytime your data changes, just call tableView's reloadData() again. It's efficient in that only the visible cells will be created, and the rest will be created whenever they are about to become visible, if ever.
Also, tableView:numberOfRowsInSection: should similarly be looking at your data to judge how many rows shall exist. It too will be called again during each call to reloadData().
Your data should always be prepared to be interrogated by the tableView delegate methods, even when it doesn't contain anything yet. When there's no data, your tableView:numberOfRowsInSection: would decide there should be 0 rows.
Upvotes: 2