UICollectionView无效索引路径崩溃

时间:2015-06-23 09:20:35

标签: ios objective-c uicollectionview nsfetchedresultscontroller

我遇到崩溃,UICollectionView尝试滚动到无效的索引路径{length = 2,path = 0 - 0}。

这是否意味着我的集合视图大小为2但我正在尝试滚动到0部分索引0?在哪种情况下,这不是一个有效的滚动?

我们已经消除了使用NSFetchedResultsController的不必要的复杂性,这可能导致崩溃,但我仍然对错误消息的读取方式及其含义感到好奇?

这是代码

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

2 个答案:

答案 0 :(得分:0)

我们也收到了很多相同的碰撞反馈, 原因是在reloadData之后立即使用scrollToItemAtIndexPath方法,我们使用此代码成功修复。

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

答案 1 :(得分:0)

我遇到了同样的问题,但我只是通过取消注释滚动功能来解决它​​。