Invalid update: invalid number of sections - ios

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (3) must be equal to the number of sections contained in the table view before the update (3), plus or minus the number of sections inserted or deleted (1 inserted, 0 deleted).'
but i insert 1 and deleted one based on data source what i missed
self.states?.append(sortedStates) //Update state property
if (self.states?.count)! > 3 {
self.states?.removeFirst()
}
self.newsFeedTableView.beginUpdates()
self.newsFeedTableView.insertSections([(self.states?.count)! - 1], with: .none)
if (self.states?.count)! > 3 {
let statesForoldestStateTime = self.states?.first
self.newestStateTime = statesForoldestStateTime?.first?.createdAt
let indexpostion = (self.states?.count)! - 3
self.newsFeedTableView.deleteSections([indexpostion], with: UITableViewRowAnimation.none)
}
self.newsFeedTableView.endUpdates()

The error says it all. When if (self.states?.count)! > 3 is false. The only section would be inserted and not deleted.
You should update your data source accordingly. The number of sections method must return someArray.count. When you insert some section, make sure to update that some array, and when you delete some section, delete the element from some array. That will resolve the issue.

Related

I tried to update after adding data to the list first, but an error occurs

DispatchQueue.main.async {
let data = try?JSONSerialization.data(withJSONObject: jsonDict["records"] as Any, options: [])
if let noticeData = try? decoder.decode([NoticeModel].self, from: data!){
for noticeAdd in noticeData {
self.noticeLists.append(Notice(title: noticeAdd.title, date: noticeAdd.createdAt, description: noticeAdd.content, isOpened: false))
self.noticeTableView.beginUpdates()
self.noticeTableView.insertRows(at: [IndexPath.init(row: self.noticeLists.count-1, section: 0)], with: .automatic)
self.noticeTableView.endUpdates()
}
}
self.chkList()
}
I tried to update after adding data but not working
'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (1) must be equal to the number of sections contained in the table view before the update (0), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'
I keep getting this error only. I don't know what is causing this error.
Can you help me?

Attempt to insert rows at specific section Swift

I have tableview and after I get new data I want to update a specific section. So I update the corresponding models. My initial value of rows in that section was 3, now it suppose to be 5. I did following:
self?.addOperations(items, completion: {(pathes) in
DispatchQueue.main.async {
print("output pathes - \(pathes)")
for (index, item) in (self?.arrValues.enumerated())!{
print("operations count - \(item.operations.count), section - \(index)")
}
self?.tableView.beginUpdates()
self?.tableView.insertRows(at: pathes, with: UITableViewRowAnimation.bottom)
self?.tableView.endUpdates()
}
})
Add operation is function that loads new data, adds it to arrValues (array that contain models of cell data), and then in completion block pass array of IndexPathObject.
That code crashes my app. In the log I can see:
output pathes - [[1, 1]]
operations count - 7, section - 0
operations count - 5, section - 1
In my second section I have 5 values for now. And output IndexPath says that I have 2 rows in section (1). But the error says:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 1. The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (3), 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).'
It all should work. Why doesn't it and how to fix it?
My delegate methods declared like this:
func numberOfSections(in tableView: UITableView) -> Int {
return arrValues.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrValues[section].operations.count
}

contentOffsetForScrollingToRowAtIndexPath in swift

i getting some response which contains some information, i stored value in dictionary format in NSMutableArray for example
{name :david, email : xxx.com},{name: david, email : yay.com},{name : david, email : zzz.com} {name: Annie, email : annie.com},{name: George, email : ger.com}
i have two label Name and Email. when i press Label Action i displayed all the usernames in that i selecting name as "daniel"
Now i going for second label called Email Action in that i want only email list of "daniel" its contains three mail i have to displayed in tableview
here i tried this code but didn't worked for me
let data = NameList.filter{($0 as! [String:String])["Name"]!.containsString(NameLabel.text!)}.map { x in return x["email"]!}
// print(data)
detailsArray = data
my output log as follows :
*** Terminating app due to uncaught exception 'NSRangeException',
reason: '-[UITableView
_contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:]: row (2) beyond bounds (1) for section (0).
The error tells you that your table does not have any row at index 2. It means that your table view consists of 2 rows and maximum range of indexPath.row can be 1 (because row index of a UITableView starts from 0). Whenever you will call a row at index path beyond range of the table, it will throw an error.

Understanding UICollectionView insertSections:

I have a UICollectionView in my iOS application. I'd like to use the various insert... methods to add data, primarily for the animations provided by iOS when using these methods (instead of reloadData:).
If I try to add a section, however, I get an exception from iOS. My code is extremely straightforward:
_regions = [NSMutableArray array];
[self.collectionView reloadData];
NSLog (#"Before attempting to add section, collection view has %ld sections", [self numberOfSectionsInCollectionView:self.collectionView]);
[_regions addObject:#"First Region"];
[self.collectionView insertSections:[[NSIndexSet alloc] initWithIndex:0]];
NSLog (#"After attempting to add section, collection view has %ld sections", [self numberOfSectionsInCollectionView:self.collectionView]);
So I add an object to my _regions array, which I use to implement the data source, then I call insertSection. My first NSLog works:
2015-03-24 11:25:39.052 MyApp[63858:17968323] Before attempting to add section, collection view has 0 sections
but then iOS throws an exception:
2015-03-24 11:25:42.082 MyApp[63858:17968323] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '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).'
I implement numberOfSectionsInCollectionView in pretty straightforward manner:
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return _regions.count;
}
If I reverse the calls (call insertSections before adding the string to the _regions array), I get a different exception:
2015-03-24 11:33:17.472 MyApp[63965:18001840] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert section 0 but there are only 0 sections after the update'
When should I modify (add an element to) _regions, relative to when I add the section to the UICollectionView?
Thanks so much for any help from experienced UICollectionView programmers . . .

How to implement NSFetchedResultsController delegate when multiple row is on deletion?

Two items is deleted.
func controller(controller: NSFetchedResultsController!, didChangeObject anObject: AnyObject!, atIndexPath indexPath: NSIndexPath!, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath!) {
switch(type) {
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
default:
break
}
}
At deletion line I get this error:
CoreData: error: Serious application error. Exception was caught
during Core Data change processing. This is usually a bug within an
observer of NSManagedObjectContextObjectsDidChangeNotification.
Invalid update: invalid number of rows in section 0. The number of
rows contained in an existing section after the update (0) must be
equal to the number of rows contained in that section before the
update (2), 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). with
userInfo (null)
*** 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 (0) must be equal to the number of
rows contained in that section before the update (2), 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).'
You need to 'batch' the updates by also implementing the controllerWillChangeContent and controllerDidChangeContent delegate methods as follows (although sorry these are Obj-c):
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
[self.tableView beginUpdates];
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
[self.tableView endUpdates];
}

Resources