Invalid number of rows in section while trying to reload using reloadsections - ios

I have two sections in the tableview.
Rows in section 0 would change when receiving remote notification (insert) or an expired timer (delete).
Section 1 would always have 8 rows and would change when user refresh, all the 8 items would be changed.
I am trying to reload the entire section 0 after the dateset has changed (use refreshed) using.
self.candidates.remoteAll()
for object in json {
let candidate = Candidate(/* Some data */)
self.candidates.append(candidate!)
}
self.tableView.reloadSections(IndexSet(integer: 1), with: .automatic)
and it somehow throws
Fatal Exception: NSInternalInconsistencyExceptionInvalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).
The number of inconsistent rows are not fixed, sometimes there are 2 before the update and 1 after, sometimes is 0 before and 1 after the update. My guess is that section 0 was inserting or delete rows while user trying to refresh section 1.
But I was trying to refresh section 1, section 0 should do no effect whether or not it has a consistent number of rows. Where am I doing wrong? Thank you.
Update
Here is numberOfRowsInSection
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
if let invitations = self.invitations {
return invitations.count
}
return 0
case 1:
return self.candidates.count
default: return 0
}
}
I am using Realm Result on section 0, and Array on section 1.

I think that in this line of code should be: self.candidates.removeAll()

Related

UICollection crash Invalid update: invalid number of sections.

The number of sections contained in the collection view after the update (1) must be equal to the number of sections contained in the collection view before the update (1), plus or minus the number of sections inserted or deleted (1 inserted, 0 deleted).
Are you basing your numberOfSections off a model of some sort? What's happening is you're inserting a section into your table view somewhere, reloading your table view data, and then the app is crashing because numberOfSections does not equal The number of sections contained in the collection view after the update.
Without seeing your code it's hard to pinpoint where the problem is, but I would do a look for where you're inserting a section and figure out how to update your numberOfSections accordingly.
A basic example would be having a stored variable like
var sectionsCount = 1
and when you insert a section, you can do sectionsCount = sectionsCount + 1 , reload your tableView data, and have :
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sectionsCount.count
}
Remember you always have to update your model that you're basing your table view off of BEFORE you reload the data.

Dispatch.main.async invalid number of rows in section

I'm having an issue when I check off my task to quickly, which makes the app crash and gives me error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (7) must be equal to the number of rows contained in that section before the update (9), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
Code when radiobutton tapped
func RadioTapped(_ cell: TableViewCell) {
if let indexPath = tableView.indexPath(for: cell) {
// Removes task from coreData
let task = self.tasks[indexPath.row]
self.context.delete(task)
do {
self.tasks = try self.context.fetch(TodayTask.fetchRequest())
(UIApplication.shared.delegate as! AppDelegate).saveContext()
// Animate the removal of task cell
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(800),execute: {
self.tableView.deleteRows(at: [indexPath], with: .fade)
})
} catch {
print("Fetching failed")
}
}
}
Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'Invalid update: invalid
number of rows in section 0. The number of rows contained in an
existing section after the update (7) must be equal to the number of
rows contained in that section before the update (9), plus or minus
the number of rows inserted or deleted from that section (0 inserted,
1 deleted) and plus or minus the number of rows moved into or out of
that section (0 moved in, 0 moved out).'
This crash means when you are deleting your table row. You are not updating your arrayCount for instance you have defined 8 inside your numberOfRowsInSection method then before you delete the row you will also need to update the rows count based on the rows you want to delete. Otherwise when your deleteRows will called it will also called the numberOfRowsInSection method and there count will mismatch and it will crash.

NSInternalInconsistencyException occurs when insertng indexPath into tableView but only when row count gets above a certain threshold

I have two tables in which I am dragging and dropping between them: sourceTableView and targetTableView. They each have their own tableViewController. A parentContainerViewController manages a 'slide out' UI which allows the user to 'longPressGesture' on the sourceTableView cell which causes sourceTableView to slide out exposing the targetTableView below at which time the user can 'drop' the dragged cell into place within the targetTableView. All works well as it should until the targetTableView grows to about 21-27 rows in size. Once we get to this size and if I re-run the project I start to get the NSInternalInconsistencyException. The detail of the error reads: reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (27) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
At first I thought I was getting a race condition issue since the number of rows before the update is "0" and after it is "27". Maybe the tableView wasn't able to load before the user drags in the item and calls the insertIndex method on tableView. But then I noticed that it works fine until we get to a certain length. Race condition wouldn't make sense in this case. Now I am thinking it has something to do with with 'visible cell' loaded vs not loaded. But why would it be '0' rows? I have looked all over for the answer. There are many NSInconsistency but none that seem to answer my specific problem.
This is the function call to tell targetTableViewController to insert an item into its datasource then tells targetTableView to insertRowsAtIndexPath :
dragDropDataSource.tableView(self, insertDataItem: item, atIndexPath: indexPath)
self.beginUpdates()
self.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
self.endUpdates()
Here is the targetTableViewController code implementing the above call:
func tableView(tableView: UITableView, insertDataItem dataItem : AnyObject, atIndexPath indexPath: NSIndexPath) -> Void {
if let di = dataItem as? DataItem {
data.insert(di, atIndex: indexPath.row)
}
data is the array that stores the 'DataItems' which are shown in the tableView rows.
Additionally. The targetTableView is initialized with data via a call in its viewDidLoad() to getMyTopTen()
func getMyTopTen() {
let pwAPI = PowWowAPI()
pwAPI.getMyTopTen(self.boardId!) {
(entries:[Entry])in
for(var i=0; i < entries.count; i++) {
let dataItem = DataItem(indexes: String(i), entry: entries[i])
self.data.append(dataItem)
}
}
dispatch_async(dispatch_get_main_queue()) {
self.targetTableView.reloadData()
}
}
I hope I have explained the problem sufficiently. If not please help me make this question better. I am new to asking questions here.

iOS Swift 2 - Error deleting tableView row

I've an error when I try to delete a row from a tableView.
The code goes like the following
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
tableView.reloadData()
}
}
The error printed from Xcode is the following:
Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).
I've read here on Stack this error but I can't figure it out.
:(
Thanks in advance.
You deleted the row from the table, but first you need to delete the corresponding datum from your data model. For example, if your data model is an array, then you might call removeAtIndex on it to remove that row. You must always proceed in this order: adjust the data model, adjust the table view.
(There is no need to reload the data at this time; you can omit that line.)

Adding row to Static UITableView: Invalid update: invalid number of rows in section 1

I'm trying to programatically insert a new row between two existing rows in my static UITableView, but it crashes saying:
'Invalid update: invalid number of rows in section 1. The number of
rows contained in an existing section after the update (6) must be
equal to the number of rows contained in that section before the
update (6), plus or minus the number of rows inserted or deleted from
that section (1 inserted, 0 deleted) and plus or minus the number of
rows moved into or out of that section (0 moved in, 0 moved out).'
This is the code I'm using to add the new row
if (indexPath.section == 1 && indexPath.row == 3) {
// If this is the first subtask we want it to appear under Sub Tasks
if (subTaskRow.count == 0) {
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 5, inSection: 1)], withRowAnimation: .Automatic)
// Added the first subtask
subTaskRow.addObject(5)
tableView.reloadData()
// Other sub tasks should appear below previous sub tasks
} else {
let row = (subTaskRow.lastObject as! Int) + 1
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: row, inSection: 1)], withRowAnimation: .Automatic)
// Keep track of subsequent subtasks
subTaskRow.addObject(row)
tableView.reloadData()
}
}

Resources