Reputation: 642
I have a chat Application in which messages are being fetched and updated in my tablview using NSFetchResultsController. Here is my code:
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
{
self.tblViewChatLog.endUpdates()
scrollToBottom(animated: true)
if self.fetchedResultsController.fetchedObjects?.count == 0 {
}
else {
}
}
func scrollToBottom(animated: Bool)
{
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1)
{
let secCount = self.tblViewChatLog.numberOfSections
if secCount > 0
{
let sections = self.fetchedResultsController.sections
let secInfo = sections?.last
let rows = secInfo?.objects //secInfo?.numberOfObjects
if (rows?.count)! > 0
{
let indexPath = NSIndexPath(row: (rows?.count)!-1, section: secCount-1)
self.tblViewChatLog.scrollToRow(at: indexPath as IndexPath, at: .bottom, animated: animated)
self.view.updateConstraintsIfNeeded()
self.tblViewChatLog.updateConstraintsIfNeeded()
}
}
}
}
I'm getting following error while trying to update my table.
Terminating app due to uncaught exception 'NSRangeException', reason: '-[UITableView _contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:]: row (1) beyond bounds (1) for section (0).'
*** First throw call stack:
(0x21f15b0b 0x216d2dff 0x21f15a51 0x2672a9c1 0x2672a45f 0x13e7b4 0x54e90 0x19adba7 0x19b78e9 0x19adb93 0x19c156d 0x19afb43 0x19b2157 0x21ed7755 0x21ed5c4f 0x21e241c9 0x21e23fbd 0x23440af9 0x2655c435 0xcc554 0x21ad0873)
libc++abi.dylib: terminating with uncaught exception of type NSException
Upvotes: 2
Views: 2601
Reputation: 2540
The error tells you that your table does not have any row at index 1. It means that your table view consists of 1 row and maximum range of indexPath.row can be 0 (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.
Upvotes: 3