ios - cellForItemAtIndexPath 被越界调用

标签 ios objective-c uicollectionview

我有一个 UICollectionView,它使用自定义 UICollectionViewCell 类。基本思想是 Collection View 将遍历目录并显示目录中包含的照片(通过 API 调用的结果)。初始 View Controller 显示一个 UICollectionView,点击单元格会生成一个带有新 UICollectionView 的新 View 。目录内容存储在 NSMutableDictionary 中,目录 ID 是键。

当使用相当短的照片列表(通常少于 30 张)创建新 View / Collection View 时会出现问题。当我旋转设备时, Collection View 尝试重新呈现,应用程序崩溃并显示“index X beyond bounds [0 .. Y]”,其中 X 是大于 Y 的数字(数组的最后一个元素)。

我注意到只有当新显示的 Collection View 的项少于“根” Collection View 时才会发生这种情况。

以下是相关(无论如何)代码的示例:

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
    return [[photos objectForKey:api.directoryID] count];
}

- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PhotoCell *photoCell = [cv dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    photoCell.photo = [[photos objectForKey:api.directoryID] objectAtIndex:indexPath.row];
    return photoCell;
}

至少,我想在 cellForItemAtIndexPath 上执行 try/catch,但不知道将 try/catch 放在哪里。也许在自定义 UICollectionView 中?

谢谢!

最佳答案

问题出在这里:

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
    return [[photos objectForKey:api.directoryID] count];
}

我假设,您为所有 UICollectionView 实例使用一个 delegatedataSource 对象。 如果是这样,请以这种方式重写您的代码:

- (NSInteger)collectionView:(UICollectionView *)view
         numberOfItemsInSection:(NSInteger)section
{
    if ( view == _firstCollectionView )
    {
        return [[photos objectForKey:api.directoryID] count];
    }
    else if ( view == _secondCollectionView )
    {
        return ...;
    }
}

您还应该以这种方式重写 collectionView:cellForItemAtIndexPath: 方法。

关于ios - cellForItemAtIndexPath 被越界调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14577093/

相关文章:

iphone - 如何检测点击时取消 UISearchDisplayController 的确切事件

iphone - 每当我使用 UIWebView loadHTMLString 时,它的 scrollView.contentOffset.y 变为 0

ios - 在上次提交后立即提交另一个 ipa 文件

ios - 如何在 iOS 中列出 uiviewcontroller 中的所有 subview ?

ios - 在 UICollectionview iOS 8 中包装单元格

ios - 如何使用自定义单元格大小提高 UICollectionView 的性能?

ios - 我可以将UITableView中的部分配置为多选吗

ios - 使用 MPVolumeView slider 调整音量时隐藏设备音量 HUD View

ios - 将 subview 添加到占据整个单元格框架的 UICollectionViewCell

ios - 如何在 Swift 中向上滚动整个表格 View ?