2828@interface HUBViewModelRenderer ()
2929
3030@property (nonatomic , strong , readonly ) UICollectionView *collectionView;
31- @property (nonatomic , strong ) id <HUBViewModel> lastRenderedViewModel;
31+ @property (nonatomic , strong , nullable ) id <HUBViewModel> lastRenderedViewModel;
3232
3333@end
3434
@@ -50,7 +50,8 @@ - (void)renderViewModel:(id<HUBViewModel>)viewModel
5050{
5151 HUBViewModelDiff *diff;
5252 if (self.lastRenderedViewModel != nil ) {
53- diff = [HUBViewModelDiff diffFromViewModel: self .lastRenderedViewModel toViewModel: viewModel];
53+ id <HUBViewModel> nonnullViewModel = self.lastRenderedViewModel ;
54+ diff = [HUBViewModelDiff diffFromViewModel: nonnullViewModel toViewModel: viewModel];
5455 }
5556
5657 HUBCollectionViewLayout * const layout = (HUBCollectionViewLayout *)self.collectionView .collectionViewLayout ;
@@ -60,10 +61,18 @@ - (void)renderViewModel:(id<HUBViewModel>)viewModel
6061
6162 [layout computeForCollectionViewSize: self .collectionView.frame.size viewModel: viewModel diff: diff];
6263
63- /* Forcing a re-layout as the reloadData-call doesn't trigger the numberOfItemsInSection:-calls
64- by itself, and batch update calls don't play well without having an initial item count. */
65- [self .collectionView setNeedsLayout ];
66- [self .collectionView layoutIfNeeded ];
64+ /* Below is a workaround for an issue caused by UICollectionView not asking for numberOfItemsInSection
65+ before viewDidAppear is called or instantly after a call to reloadData. If reloadData is called
66+ after viewDidAppear has been called, followed by a call to performBatchUpdates, UICollectionView will
67+ ask for the initial number of items right before the batch updates, and for the new count while inside
68+ the update block. This will often trigger an assertion if there are any insertions / deletions, as
69+ the data model has already changed before the update. Forcing a layoutSubviews however, manually
70+ triggers the numberOfItems call.
71+ */
72+ if (usingBatchUpdates && diff == nil ) {
73+ [self .collectionView setNeedsLayout ];
74+ [self .collectionView layoutIfNeeded ];
75+ }
6776 completionBlock ();
6877 } else {
6978 void (^updateBlock)() = ^{
0 commit comments