Swift UICollectionViewController:由于未捕获的异常而终止应用程序';n内部一致性异常';

Swift UICollectionViewController:由于未捕获的异常而终止应用程序';n内部一致性异常';,swift,firebase,uicollectionview,uicollectionviewcell,firebase-realtime-database,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() // Registe

原因:“尝试将项目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通过调用返回
1
numberOfSectionsInCollectionView
检查数据的一致性时,它会注意到不一致性

将要插入的节号更改为
0

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

虽然
nsindepath(forRow:instation:)
将返回完全相同的结果,但您应该为CollectionView使用
nsindepath(forItem:instation:)
。这是修复一系列错误的最后一步,这些错误花了我几天的时间才弄清楚,谢谢!也谢谢你的额外提示。