I'v got a UITableView whose dataSource updated at random intervals in a very short period of time. As more objects are discovered, they are added to the tableView's data source and I insert the specific indexPath:
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView endUpdates];
The data source is located in a manager class, and a notification is posted when it changes.
- (void)addObjectToDataSource:(NSObject*)object {
[self.dataSource addObject:object];
[[NSNotificationCenter defaultCenter] postNotification:@"dataSourceUpdate" object:nil];
}
The viewController updates the tableView when it receives this notification.
- (void)handleDataSourceUpdate:(NSNotification*)notification {
NSObject *object = notification.userInfo[@"object"];
NSIndexPath *indexPath = [self indexPathForObject:object];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView endUpdates];
}
This works fine, but I noticed that in some cases, a second object is discovered just as the first one is calling endUpdates, and I get an exception claiming I have two objects in my data source when the tableView was expecting one.
I was wondering if anyone has figured out a better way to atomically insert rows into a tableView. I was thinking of putting a @synchronized(self.tableView) block around the update, but I'd like to avoid that if possible because it is expensive.