Skip to content

Commit 531c05c

Browse files
committed
Fix NSInternalInconsistencyException related to the number of items in the collection view when using FUIFirestoreCollectionViewDataSource
1 parent f79849d commit 531c05c

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

FirebaseFirestoreUI/FUIFirestoreCollectionViewDataSource.m

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,15 @@ @interface FUIFirestoreCollectionViewDataSource () <FUIBatchedArrayDelegate>
2424

2525
@property (nonatomic, readonly, nonnull) FUIBatchedArray *collection;
2626

27+
// We need to maintain our own count property because the self.collection.count is sometimes
28+
// inconsistent with how the -[UICollectionView performBatchUpdates:] method expects it to work.
29+
// -[UICollectionView performBatchUpdates:] calls -[UICollectionViewDataSource count] at the
30+
// beginning and at the end of the method, and if the value of -[UICollectionViewDataSource count]
31+
// after -[UICollectionView performBatchUpdates:] is not equal to the value of
32+
// -[UICollectionViewDataSource count] before + (rows added - rows deleted) it throws an
33+
// NSInternalInconsistencyException.
34+
@property (nonatomic) NSUInteger count;
35+
2736
/**
2837
* The callback to populate a subclass of UICollectionViewCell with an object
2938
* provided by the datasource.
@@ -46,6 +55,7 @@ - (instancetype)initWithCollection:(FUIBatchedArray *)collection
4655
_collection = collection;
4756
_collection.delegate = self;
4857
_populateCellAtIndexPath = populateCell;
58+
_count = 0;
4959
}
5060
return self;
5161
}
@@ -58,10 +68,6 @@ - (instancetype)initWithQuery:(FIRQuery *)query
5868
return [self initWithCollection:array populateCell:populateCell];
5969
}
6070

61-
- (NSUInteger)count {
62-
return self.collection.count;
63-
}
64-
6571
- (NSArray<FIRDocumentSnapshot *> *)items {
6672
return self.collection.items;
6773
}
@@ -131,7 +137,9 @@ - (void)batchedArray:(FUIBatchedArray *)array
131137
[insertedIndexPaths addObject:inserted];
132138
}
133139
[self.collectionView insertItemsAtIndexPaths:insertedIndexPaths];
134-
140+
141+
self.count += insertedIndexPaths.count;
142+
self.count -= deletedIndexPaths.count;
135143
} completion:^(BOOL finished) {
136144
// Reload paths that have been moved.
137145
NSMutableArray *movedIndexPaths =
@@ -170,7 +178,7 @@ - (NSInteger)numberOfSectionsInCollectionView:(nonnull UICollectionView *)collec
170178

171179
- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView
172180
numberOfItemsInSection:(NSInteger)section {
173-
return self.collection.count;
181+
return self.count;
174182
}
175183

176184
@end

0 commit comments

Comments
 (0)