UICollectionView invalid index path crash

4.4k Views Asked by At

I am having a crash with UICollectionView attempt to scroll to invalid index path {length = 2, path = 0 - 0}.

Does this mean that my collection view is of size 2 but i'm trying to scroll to section 0 index 0? In which case wouldn't that be a valid scroll?

We have since taken out the unnecessary complication of using an NSFetchedResultsController which could have been causing the crash but i'm still curious about how the error message reads and what it means?

This was the code

void fetch() {

   // get data from core data using a FetchRequest
   do a perform fetch to get my item

   // loop through to see which index the item I want is at
   loop through result {
      if (my id matches core data id) {
          self.selectedIndex = x;
       }
    }

    // get more from core data using a Fetch Request
    create another FetchedResultsController
    do another fetch to get all other items

    [self.myCV reloadData];

    // find the index path for the item I want to scroll to
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.selectedIndex inSection:0];

    [self.myCV scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally | UICollectionViewScrollPositionCenteredVertically animated:NO];
}

// UICollectionView delegate methods
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return [[self.fetchedResultsController sections] count];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    id<NSFetchedResultsSectionInfo> secInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    return [secInfo numberOfObjects];
}
3

There are 3 best solutions below

0
On

i was stucked in same issue but i resolved it by uncommenting scroll function just.

1
On

This solution help me for simular case:

static var animatingDifferences: Bool {
        if #available(iOS 15.0, *) {
            return true
        } else {
            return false
        }
    }
... // in snapshot applying method:
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
...
// false animations solve crush for iOS 14
apply(snapshot, animatingDifferences: Self.animatingDifferences)

1
On

We also received a lot of the same crash feedback, The reason is to use the scrollToItemAtIndexPath method immediately after reloadData, We use this code to successfully fix.

[self.myCV reloadData];
[self.myCV.collectionViewLayout invalidateLayout];
if (self.myCV.numberOfSections != 0) {
     NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.selectedIndex inSection:0];
    [self.myCV scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally | UICollectionViewScrollPositionCenteredVertically animated:NO];
}