ios - UICollectionView 无效索引路径崩溃

标签 ios objective-c uicollectionview nsfetchedresultscontroller

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

这是否意味着我的 Collection View 大小为 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];
}

最佳答案

我们也收到了很多相同的崩溃反馈,
原因是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];
} 

关于ios - UICollectionView 无效索引路径崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30998788/

相关文章:

ios - 使用 Photo Kit 和 Swift 在 UICollectionViewCell 中模糊图像

ios - 当 ViewController 已经有委托(delegate)时如何设置委托(delegate)?

mysql - 从 MySQL 获取数据库到 SQLite

ios - 使用 Core Location 在后台执行功能是否合适?

objective-c - 您如何测量 iOS 线程的实际 on-CPU 时间?

IOS UICollectionView 和 UIScrollView 回收问题

swift - 关闭 UIViewController 后 UI 卡住 5 秒

ios - 我应该忽略 git 中的 UnserInterfaceState 和 xcschememanagement 文件吗?

ios - 如何在 Objective-C 中设置 Http header 字段?

ios - 具有不同自动旋转选项的屏幕