swift - UICollectionViewController : Terminating app due to uncaught exception 'NSInternalInconsistencyException'

标签 swift firebase uicollectionview uicollectionviewcell firebase-realtime-database

原因:'试图将项目 0 插入第 1 部分,但更新后只有 1 个部分'

我不明白这是什么问题。如果数组被插入第 1 节并且(只有)1 个节那么为什么不能插入?

var ref: FIRDatabaseReference!
var messages: [FIRDataSnapshot]! = []
private var refHandle: FIRDatabaseHandle!

override func viewDidLoad() {
    super.viewDidLoad()

    // Register cell classes
    collectionView?.registerClass(ChatLogCollectionCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    collectionView?.backgroundColor = UIColor.blueColor()
}

override func viewWillAppear(animated: Bool) {
    self.messages.removeAll()
    collectionView?.reloadData()
    refHandle = self.ref.child("messages").observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in
        self.messages.append(snapshot)
        print(self.messages.count) //temp
        self.collectionView?.insertItemsAtIndexPaths([NSIndexPath(forRow: self.messages.count - 1, inSection: 1)])
    })
}

单元格代码:

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
}

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.messages.count
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ChatLogCollectionCell
}

最佳答案

您正在向 1 部分插入内容,这意味着必须有 2 部分,因为编号从 0 开始。当 iOS 通过调用返回 1numberOfSectionsInCollectionView 检查数据的一致性时,它会注意到不一致。

将要插入的节号更改为 0

self.collectionView?.insertItemsAtIndexPaths([NSIndexPath(forItem: self.messages.count - 1, inSection: 0)])

关于swift - UICollectionViewController : Terminating app due to uncaught exception 'NSInternalInconsistencyException' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38164911/

相关文章:

ios - UIWebView 可以在不成为第一响应者的情况下处理用户交互吗?

ios - 如何将值从tableview传递到collectionview

ios - Swift3中如何根据内容自动改变UICollectionView Cell的高度?

ios - 在标签栏中推送 View Controller

arrays - 在 Swift 中遍历 UInt8 整数数组;对数组的子集执行计算

ios - JSON 没有快速更新

java - 如何在 firebase 中创建条件

ios - 基本从 Firebase 读取并用结果加载 TableView (Swift)

swift - 从cloud firestore下载图像并添加到用户对象

uicollectionview - UICollectionViewFlowLayout 的行为未定义,因为单元格宽度大于 collectionView 宽度