About7Deaths
About7Deaths

Reputation: 691

UICollectionViewController: Terminating app due to uncaught exception 'NSInternalInconsistencyException'

Reason: 'attempt to insert item 0 into section 1, but there are only 1 sections after the update'

I don't understand what the problem is. If the array is being inserted into section 1 and there is (only) 1 section then why can it not be inserted?

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)])
    })
}

Cell Code:

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
}

Upvotes: 1

Views: 702

Answers (1)

vacawama
vacawama

Reputation: 154613

You are inserting something into section 1, which means there must be 2 sections because numbering starts at 0. When iOS checks the consistency of your data by calling numberOfSectionsInCollectionView which returns 1, it notes the inconsistency.

Change the section number you are inserting into to 0.

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

Upvotes: 1

Related Questions