由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:“试图滚动到无效 索引路径:{length = 2,路径= 0-9}'
我收到这个错误,我想我需要做一个警惕,或者如果让let声明以避免崩溃,但是做这种声明的最佳地点在哪里?
func observeMessages() {
guard let uid = Auth.auth().currentUser?.uid, let toId = user?.id else {
return
}
let userMessagesRef = Database.database().reference().child("user-messages").child(uid).child(toId)
userMessagesRef.observe(.childAdded, with: { (snapshot) in
let messageId = snapshot.key
let messagesRef = Database.database().reference().child("messages").child(messageId)
messagesRef.observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String: AnyObject] else {
return
}
self.messages.append(Message(dictionary: dictionary))
DispatchQueue.main.async(execute: {
self.collectionView?.reloadData()
//scroll to the last index
let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
self.collectionView?.scrollToItem(at: indexPath, at: .bottom, animated: true)
})
}, withCancel: nil)
}, withCancel: nil)
}
答案 0 :(得分:1)
请如下更新您的代码...
您正在后台更新self.message
。进入主线程
func observeMessages() {
guard let uid = Auth.auth().currentUser?.uid, let toId = user?.id else {
return
}
let userMessagesRef = Database.database().reference().child("user-messages").child(uid).child(toId)
userMessagesRef.observe(.childAdded, with: { (snapshot) in
let messageId = snapshot.key
let messagesRef = Database.database().reference().child("messages").child(messageId)
messagesRef.observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String: AnyObject] else {
return
}
DispatchQueue.main.async(execute: {
self.messages.append(Message(dictionary: dictionary))
self.collectionView?.reloadData()
//scroll to the last index
let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
self.collectionView?.scrollToItem(at: indexPath, at: .bottom, animated: true)
})
}, withCancel: nil)
}, withCancel: nil)
}