Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update UITableView at run time, after the view is loaded

I have read several articles about UITableView, including the official doc and some on SO. But my situation seems to be different.
I want to update the Table each time the view loaded. And I must fetch the data using HTTP request.
What I got now is:

  1. When enter the table view, I should use a non-synchronous HTTP request to update the data. Because I don't want the main thread to wait. One place to do that, is in the tableView:cellForRowAtIndexPath: method. So I return 0 for no data exist at the beginning.
  2. When I get the HTTP respond, I update rows on main thread using beginUpdates endUpdates insertRowsAtIndexPaths:withRowAnimation:
  3. And I must update the "Data Source" at the same time, but how to do that?
    Or should I make a daemon thread and update my data every once in a while? So that the data will be ready when TableView is loaded.
like image 551
Nickolas Avatar asked Dec 19 '11 12:12

Nickolas


3 Answers

You would do it like this:

  • Have a boolean or some variable where you can reliably detect whether you have all the data.
  • In viewWillAppear, reset everything. Start loading your data.
  • If you don't have the data yet, you only display one section with one cell (a placeholder cell that reads "Loading..." and shows a spinner, for instance).
  • Once the data is completely loaded, you set the bool or whatever.
  • Call [self.tableView reloadData];

In all of your UITableViewDataSource methods you would need to check whether you've got the data already or not. If not, you return the placeholder data.

like image 184
DarkDust Avatar answered Nov 15 '22 19:11

DarkDust


[yourtablename reloadData]; will help you relaod the data in the tableview, You can call this once you get the response from your server

like image 25
Nakkeeran Avatar answered Nov 15 '22 19:11

Nakkeeran


I'm not sure there's a "best method" for what you're trying to accomplish here. I would suggest trying the method you have, and seeing if it provides an adequate user experience (whatever that means to you) and if it doesn't, try something else. I would definitely suggest having some sort of "loading" indicator while the table is empty and waiting for http response.

In terms of your question about the "data source", the data source of a UITableView is simply an object that implements the UITableViewDataSource protocol which you can read about here. Often times, you will have XCode set up a UITableViewController object which will act as both delegate and data source to your table view. How you actually store your data is up to you. The data source protocol simply provides the methods by which a table view will "ask" for the data it needs to load.

like image 39
Sean Avatar answered Nov 15 '22 19:11

Sean