NSRangeException, reason: 'Attempted to scroll the table view to an out-of-bounds...'

12.3k Views Asked by At

Got a UITableView that I'm populating with ChatMessage objects, that I keep in a Dictionary that is grouped by date sent like so var groupedMessages = [Date : [ChatMessage]]() I'm also keeping keys in var keys = [Date]()

Setting sections and dequeueing into rows works just fine. Also insertRows below works and adds the message as a new UITableViewCell as expected and at the correct position.

However, the App crashed at the scrollToRow call with error NSRangeException, reason: 'Attempted to scroll the table view to an out-of-bounds row (2) when there are only 2 rows in section 1.

    @IBAction func sendMessage(_ sender: Any) {

            // create new ChatMessage object
            var newMessage = ChatMessage()
            let now = Date()
            newMessage.tsp = now
            newMessage.message = self.MessageTextField.text
            newMessage.sender = Globals.shared.user

            // append to grouped messages
            self.groupedMessages[self.keys.last!]?.append(newMessage)
            var path = IndexPath(row: self.groupedMessages[self.keys.last!]!.count-1, section: self.keys.count-1)
            print("PATH: ", path)
            self.MessageList.beginUpdates()
            self.MessageList.insertRows(at: [path], with: .fade)
            print("PATH 2: ", path)
            self.MessageList.scrollToRow(at: path, at: .bottom, animated: true)
            self.MessageList.endUpdates()

            // call api to store sent message
            ...

        }
2

There are 2 best solutions below

2
Bernhard Engl On

The problem I had was that I tried to scroll before finishing the update. Corrected code:

// append to grouped messages
        self.groupedMessages[self.keys.last!]?.append(newMessage)
        var path = IndexPath(row: self.groupedMessages[self.keys.last!]!.count-1, section: self.keys.count-1)
        self.MessageList.beginUpdates()
        self.MessageList.insertRows(at: [path], with: .fade)
        self.MessageList.endUpdates()
        self.MessageList.scrollToRow(at: path, at: .bottom, animated: true)
0
Kunal Sharma On

In my case, I forget to add delegate, and datasource of table view. After adding this, my code started working.

This error occurs because your table is not able to find the data or cell.