Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redraw UITableView after updating data async

I have a UITableview that I load with data async so the tableview might appear without data.
I have tired the ReloadData method but the tableview remains empty until I scroll the tableview, suddenly the data appears.
The same thing happens when I load a tableview as a detailedview and switching between items, the previoud items data appears first and as soon as I scroll in the table view it shows the correct data.
My guess is that the ReloadData method works just fine, but I need to redraw the tableview somehow, any suggestions on how to solve this?

/Jimmy

like image 647
Jimmy Engtröm Avatar asked Feb 23 '10 23:02

Jimmy Engtröm


2 Answers

You said you're populating content asynchronously but did you invoke the reloadData in the context of the main thread ? (and not via the thread that populates the content)

Objective-C

[yourUITableView performSelectorOnMainThread:@selector(reloadData)
                                  withObject:nil 
                               waitUntilDone:NO];

Swift

dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() })

Monotouch

InvokeOnMainThread(() => this.TableView.ReloadData());
like image 67
yonel Avatar answered Nov 10 '22 16:11

yonel


Yonels answer is perfect when your view is currently visible to the user (e.g: User presses a reload button which populates your UITableView.)

However, if your data is loaded asynchronously and your UITableView is not visible during the update (e.g: You add Data to your UITableView in another View and the UITableView is displayed later by userinput), simply override the UITableViewController's viewWillAppear method.

- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.tableView reloadData];
}

The positive effect is that your UITableView only reloads it's data once when the user actually want's to see it, not when new items are added.

like image 4
Jay Avatar answered Nov 10 '22 17:11

Jay