UICollectionViewController:由于未捕获的异常而终止应用程序' NSInternalInconsistencyException'

时间:2016-07-02 22:17:09

标签: 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 个答案:

答案 0 :(得分:1)

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

将您要插入的部分编号更改为1

0