【发布时间】:2018-11-29 14:06:00
【问题描述】:
由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'试图滚动到无效 索引路径:{length = 2, path = 0 - 9}'
我收到了这个错误,我猜我需要做一个 guard 或者 if 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)
}
【问题讨论】:
-
您是否尝试过调试您的索引路径调用?您用什么值调用它,调用时的有效值是什么?
-
让 indexPath = IndexPath(item: self.messages.count - 1, section: 0) indexpath 应该是可选的,让 indexPath : IndexPath? = 等等...
标签: swift