Khoury Khoury - 1 year ago 103
Swift Question

How to create new cell in UICollectionView without 'NSInternalInconsistencyException' error

How do I create a new cell without this error

'NSInternalInconsistencyException', reason: 'attempt to insert item 2 into section 0, but there are only 2 items in section 0 after the update'

Here is the code to create new cell

@IBAction func SetDate(sender: AnyObject) {

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let day =
let datestring = dateFormatter.stringFromDate(day)

let text = textField.text

let image = userDefault.objectForKey("image") as! String


dismissViewControllerAnimated(true, completion: nil)


Here is how the date from the previous code is used in my app

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell

cell.sinceLabel.text = Globals.sinceLabelArray[indexPath.item]
cell.myBackground.image = UIImage(named: String(Globals.imagesArray[indexPath.item]))

let day = Globals.datesArray[indexPath.item]
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

let date1: NSDate = dateFormatter.dateFromString(day)!
let diffDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Day], fromDate: date1, toDate: date2, options: NSCalendarOptions.init(rawValue: 0))
cell.dayCountLabel.text = String("\(abs(")

cell.backgroundColor = UIColor.blackColor()

return cell

Here is how I am reloading data

func loadList(notification: NSNotification){
let count = Globals.datesArray.count
let index = count > 0 ? count - 1 : count
let indexPath = NSIndexPath(forItem: index, inSection: 0)


Here is the code for determining number of cells to make

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

return count

var count = Globals.datesArray.count as Int

Some extra details:
(1) The SetDate() saves string to three static var arrays, within a struct.
(2) Those arrays are empty, to my knowledge.


Sam Sam
Answer Source

Replace your code in loadList with just


or if you want to do it as a batch update :

        }, completion: nil)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download