Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView begin/end updates

When using - (void)beginUpdates and - (void)endUpdates on a UITableView do you have to make the changes to the datasource inside calls?

i.e.

If I have a NSMutableArray called dataSource driving my tableView could I do this...

// edit the actual data first
[dataSource addObject:@"Blah"];

// now update the table
[self.tableView beginUpdates];

[self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:dataSource.count - 1 inSection:0] withRowAnimation:UITableViewRowAnimationAutomatic];

[self.tableView endUpdates];

Or is it necessary to do...

[self.tableView beginUpdates];

[dataSource addObject:@"Blah"];

[self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:dataSource.count - 1 inSection:0] withRowAnimation:UITableViewRowAnimationAutomatic];

[self.tableView endUpdates];

Just asking because I have a couple places where I am updating and I could potentially take the common code out to a function.

But only if I can update outside the update calls.

like image 543
Fogmeister Avatar asked Aug 28 '13 08:08

Fogmeister


People also ask

What class does UITableView inherit from?

The tableview is the instance of the UITableView class, which inherits the UIScrollView class.

What does tableView beginUpdates do?

beginUpdates()Begins a series of method calls that insert, delete, or select rows and sections of the table view.

What is a UITableView?

UITableView manages the basic appearance of the table, but your app provides the cells ( UITableViewCell objects) that display the actual content. The standard cell configurations display a simple combination of text and images, but you can define custom cells that display any content you want.


2 Answers

It is generally a good idea to update the datasource in between tableView beginUpdates/endUpdates. After the endUpdates is called, the OS will trigger the dataSource calls to get the sections and row counts. If at that point, the datasource has not been updated, then you may get tableView inconsistency crashes.

It may work in some cases to update the datasource before the tableView beginUpdates/endUpdates call, however you must make sure that you are updating the datasource in the same thread and on the same run loop. Since tableView updates must be done on the main thread, that means you have to make your datasource updates on the main thread.

If you update the datasource, and don't immediately do your tableView updates (and you do something like rotate the screen), then you can get a tableView inconsistency crash.

like image 119
Thuan Nguyen Avatar answered Sep 22 '22 18:09

Thuan Nguyen


I have always used 1st approach and it causes no problem. just make sure that after changing data source, immediately update your table.

like image 33
NightFury Avatar answered Sep 20 '22 18:09

NightFury