user3462448 user3462448 - 10 months ago 61
iOS Question

inserting row into a tableview from viewdidload

i have a uiviewcontroller with a tableview in it. im trying to query through users in my firebase data base but i keep getting this error:

'NSInternalInconsistencyException', reason: 'attempt to insert row 1 into section 0, but there are only 0 rows in section 0 after the update'

i looked it up and tried the beginUpdates and endUpdates methods but get the same error on the line that i call endUpdates. any ideas why this is happening?

heres my code:

searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.definesPresentationContext = true
definesPresentationContext = true
self.browseTable.tableHeaderView = searchController.searchBar

ref.child("users").queryOrdered(byChild: "name").observe(.childAdded, with: { (snapshot) in

self.usersArray.append(snapshot.value as? NSDictionary)

//insert rows

//where the error occurs
self.browseTable.insertRows(at: [IndexPath(row:self.usersArray.count - 1,section: 0)], with: .automatic)


}) { (error) in
print("ERROR: \(error.localizedDescription)")


Answer Source

As discussed in the comments regarding the problem, the crash is caused due to the value returned in the function func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int not matching the number of rows after inserting rows.

In cases like this where your value returned in numberOfRowsInSection function is based on your dataSource object, updating your dataSource object before inserting/deleting rows will resolve the problem.

Feel free to suggest edits :)