什么是确保UITableView自动重新加载的最好方法?

我有一个UITableView的dataSource在很短的时间内随机更新。 随着更多的对象被发现,它们被添加到tableView的数据源,我插入特定的indexPath:

[self.tableView beginUpdates]; [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; [self.tableView endUpdates]; 

数据源位于pipe理员类中,并在更改时发布通知。

 - (void)addObjectToDataSource:(NSObject*)object { [self.dataSource addObject:object]; [[NSNotificationCenter defaultCenter] postNotification:@"dataSourceUpdate" object:nil]; } 

viewController在接收到这个通知时更新tableView。

 - (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]; } 

这工作正常,但我注意到,在某些情况下,第二个对象被发现就像第一个调用endUpdates,并得到一个exception,声称我有两个对象在我的数据源时,tableView期待。

我想知道是否有人已经想出了一个更好的方式primefaces插入行到tableView。 我正在考虑在更新中添加一个@synchronized(self.tableView)块,但是如果可能的话,我想避免这种情况,因为它很昂贵。

我推荐的方法是创build一个专用队列,用于同步将批量更新发布到主队列上( addRow是在给定indexPath处将数据项插入数据模型的方法):

 @interface MyModelClass () @property (strong, nonatomic) dispatch_queue_t myDispatchQueue; @end @implementation MyModelClass - (dispatch_queue_t)myDispatchQueue { if (_myDispatchQueue == nil) { _myDispatchQueue = dispatch_queue_create("myDispatchQueue", NULL); } return _myDispatchQueue; } - (void)addRow:(NSString *)data atIndexPath:(NSIndexPath *)indexPath { dispatch_async(self.myDispatchQueue, ^{ dispatch_sync(dispatch_get_main_queue(), ^{ //update the data model here [self.tableView beginUpdates]; [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; [self.tableView endUpdates]; }); }); } 

通过这样做,您不会阻塞任何其他线程,并且基于块的方法可以确保表视图的animation块(即抛出exception的块)以正确的顺序执行。 快速行插入到UITableView导致NSInternalInconsistencyException中有一个更详细的说明。