由于意外异常而终止应用程序
'NSInvalidArgumentException',reason:'尝试滚动到无效
索引路径:{length=2,path=0-9}'
我收到这个错误我猜我需要做一个守卫或者如果让语句来避免崩溃,但是在哪里做这样的语句最好呢?
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)
}
最佳答案
请更新你的代码如下。。。
您正在后台更新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)
}
关于swift - 未捕获的异常“NSInvalidArgumentException”,原因:“试图滚动到无效的索引路径,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50948226/