What can cause the error “Assertion failure in -[UICollectionViewData numberOfItemsBeforeSection:]”?

472 views Asked by At

Here is my code snippet:

NSIndexSet *indexSet =  self.selectedIndexSet;
__block SGPhotoSelectorCell *cell;

[indexSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {

    NSLog(@"%lu", (unsigned long)idx);
    ***NSIndexPath *indexPath = [NSIndexPath indexPathWithIndex:idx];***

    cell = (SGPhotoSelectorCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.numLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)idx];

    [collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
}];

What is the reason for this error?

“Assertion failure in -[UICollectionViewData numberOfItemsBeforeSection:]”

1

There are 1 answers

0
iAnchor On

I think this problem is very simple if you are careful. Please have a look at the cause of crash again. “Assertion failure in -[UICollectionViewData numberOfItemsBeforeSection:]”, Meaning is the section of the item was not found, So You should use "NSIndexPath *indexPath = [NSIndexPath indexPathForItem:idx inSection:0];" replace " *NSIndexPath indexPath = [NSIndexPath indexPathWithIndex:idx];". Okey, Bingo