【问题标题】:NSInvalidArgumentException, reason: no object at index in section at index. UICollectionViewController and NSFetchedResultsControllerNSInvalidArgumentException,原因:索引部分中的索引处没有对象。 UICollectionViewController 和 NSFetchedResultsController
【发布时间】:2017-01-13 06:21:31
【问题描述】:

尝试在我的UICollecitonView 末尾添加一个“添加新”按钮。 与CoreData 合作。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionCell
    configureCell(cell: cell, indexPath: indexPath)

    var numberOfItems = self.collectionView(self.collectionView, numberOfItemsInSection: 0)

    if (indexPath.row == numberOfItems - 1) {            
        var addCellButton = UIButton(frame: cell.frame)
        addCellButton.setTitle("Add", for: UIControlState.normal)

        cell.addSubview(addCellButton)
    }
    return cell
} 

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if let sections = controller.sections {
        let sectionInfo = sections[section]
        return sectionInfo.numberOfObjects + 1
    }
    return 0
}

错误:“NSInvalidArgumentException”,原因:“索引 0 部分中索引 3 处没有对象”

我需要检查NSFetchedResultsController 的边界吗? 如此处提议:Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no object at index 3 in section at index 0'

【问题讨论】:

  • 请注意:在cellForItemAt 中,您(大部分)总是一次又一次地添加addCellButton,因为单元格被重复使用......您应该在一个单元格中只执行一次。以后你可以隐藏它,或者你应该删除它。
  • 你在哪一行得到错误?
  • @muescha 我在 AppDelegate 类中遇到一般错误:UIResponder, UIApplicationDelegate ... 尝试使用打印并了解有关错误的更多信息,但不知道在哪里以及如何。
  • @muescha 关于按钮 - 我希望按钮始终位于 CollectionView 的末尾,所以我认为,每次都需要创建它,不是吗?
  • 没有。单元格被重复使用。所以重用的单元格仍然有之前使用时添加的 Button。您可以在 3d 调试视图中检查这一点。您只看到一个按钮,因为其他按钮就在添加的新按钮下方

标签: ios swift core-data


【解决方案1】:

您告诉UICollectionView,您在该部分中比NSFetchedResultsController 中存储的项目多出一项。

我相信当您尝试从configureCell 方法访问NSFetchedResultsController.object(at: IndexPath) 以获取您所说的那个“额外”项目时会引发异常。

如果您希望“添加新”按钮与所有其他按钮显示在相同类型的单元格中,则应停止在 collectionView(numberOfItemsInSection:) 中添加额外的项目

或者,您可以创建一个不同类型的单元格放在末尾,只需添加新按钮,然后在使单元格出列之前移动 if 语句。如果要填充最后一项,则使用按钮将“AddNew”单元格标识符出列。否则,您将“单元”标识符出列并将其配置为显示来自NSFetchedResultsController 的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多