Crush when call addItem()

When I click the “add” on screen, the program crushes, the error says “checklist[17372:1000930] *** Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘attempt to insert row 5 into section 0, but there are only 5 rows in section 0 after the update’”

Here is my code, can anyone give me some clue?

    @IBAction func addItem() {
    let newRowIndex = items.count
    let item = ChecklistItem()
    item.checked = false
    item.text = "I'm a new item"
    let indexPath = NSIndexPath(forRow: newRowIndex, inSection: 0)
    let indexPaths = [indexPath]
    print("\(items[5].text)") // print "I'm a new item"
    print("have \(items.count) items") // print 6
    print("The indexPath is \(indexPaths[0].row)") // print 5
    tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)

Many thanks!

@jiang Thanks very much for posting. I found similar questions on StackOverflow that might have the answer(s) for you:

StackOverflow Answer 1

StackOverflow Answer 2

I hope this helps :wink:

All the best!

Thanks mate!

I found the problem, in this function:

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5

Change the return value to items.count, so the number of rows dynamically updates

@jiang Good stuff! I’m happy to see that your problem was resolved. I had a suspicion that the problem was connected to your array, and its relationship with your UITableView, but couldn’t say for certainty given the small code block you provided.

One teacher told me many years ago that the best way to learn a concept is when you figure out the problem yourself instead of having someone show it to you, and you did precisely that!

All the best :slight_smile:

1 Like

This topic was automatically closed after 166 days. New replies are no longer allowed.